]> git.codecow.com Git - libnemo.git/commitdiff
Extend hex validation to check length.
authorChris Duncan <chris@codecow.com>
Sat, 8 Aug 2026 17:18:34 +0000 (10:18 -0700)
committerChris Duncan <chris@codecow.com>
Sat, 8 Aug 2026 17:18:34 +0000 (10:18 -0700)
src/lib/convert/hex.ts

index e4237c9e78bd937435388e73dfbdb09187615dc7..cdd03a3b6fa386e2389155dd41e1d1557553a394 100644 (file)
@@ -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)
        },
 
        /**