From: Chris Duncan Date: Sat, 8 Aug 2026 17:18:34 +0000 (-0700) Subject: Extend hex validation to check length. X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=f38d26a5414cffadce4fe4d2776eb0859e51ec58;p=libnemo.git Extend hex validation to check length. --- diff --git a/src/lib/convert/hex.ts b/src/lib/convert/hex.ts index e4237c9..cdd03a3 100644 --- a/src/lib/convert/hex.ts +++ b/src/lib/convert/hex.ts @@ -6,10 +6,18 @@ export const hex = Object.freeze({ * Check if input is a valid hexadecimal string. * * @param {unknown} input - Variable to check + * @param {number} [length] - Exact even-parity length of the input * @returns True if input is hex, else false */ - is (input: unknown): input is Hex { - return typeof input === 'string' && /^([0-9A-F]{2})+$/i.test(input) + is (input: unknown, length?: number): input is Hex { + if (typeof length !== 'undefined') { + if (!Number.isSafeInteger(length) || length < 0 || length & 1) { + throw new TypeError(`Invalid "length" argument`) + } + } + const quantifier = length ? `{${length >> 1}}` : '+' + const pattern = new RegExp(`^([0-9A-F]{2})${quantifier}$`, 'i') + return typeof input === 'string' && pattern.test(input) }, /**