From 67307a1e1eeff7d4e7cf9ed8d26108d990630913 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Thu, 19 Jun 2025 00:28:00 -0700 Subject: [PATCH] Add utilities to check hex values. --- src/utils/index.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/utils/index.ts b/src/utils/index.ts index fa4cc8a..795e7d0 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -30,6 +30,47 @@ type Averages = { truncatedHarmonic: number, } +/** +* Checks if value is a string representing an N-byte hexadecimal number. +* +* @param {unknown} value - Value to check. +* @param {(number|null)} byteLength - Number of bytes the string should represent, or 'null' for any number greater than zero. +* @returns True if value is a 2N-character hexadecimal string, else false. +*/ +export function isHexN (value: unknown, byteLength: number | null): value is string { + if (typeof value !== 'string') return false + const v = value.replace(/^0[Xx]/, '') + const length = byteLength === null ? '+' : `{${2 * byteLength}}` + const r = new RegExp(`^[A-Fa-f\\d]${length}\$`) + return r.test(v) +} + +/** +* Checks if value is a string representing an 8-byte hexadecimal number. +* +* @param {unknown} value - Value to check. +* @returns True if value is a 16-character hexadecimal string, else false. +*/ +export function isHex8 (value: unknown): value is string { + return isHexN(value, 8) +} + +/** +* Checks if value is a string representing a 32-byte hexadecimal number. +* +* @param {unknown} value - Value to check. +* @returns True if value is a 64-character hex string, else false. +*/ +export function isHex32 (value: unknown): value is string { + return isHexN(value, 32) +} + +/** +* Computes various types of averages for a set of numbers. +* +* @param {number[]} times - List of numbers, often timing durations. +* @returns Object with averaged values for the specified list. +*/ export function stats (times: number[]): Averages | null { if (times == null || times.length === 0) return null -- 2.47.3