Re-add ignoreLength (#1199)

* Re-add ignoreLength

* Actual ignore
This commit is contained in:
Jaco
2021-11-17 13:48:07 +02:00
committed by GitHub
parent ee0436a612
commit 4efd88869d
2 changed files with 21 additions and 2 deletions
+9
View File
@@ -59,4 +59,13 @@ describe('isHex', (): void => {
isHex('0x1234', 8)
).toEqual(false);
});
it('does ignore lengths as required', (): void => {
expect(
isHex('0x123')
).toEqual(false);
expect(
isHex('0x123', -1, true)
).toEqual(true);
});
});
+12 -2
View File
@@ -7,6 +7,8 @@ export const REGEX_HEX_PREFIXED = /^0x([\da-fA-F]{2})+$/;
export const REGEX_HEX_NOPREFIX = /^([\da-fA-F]{2})+$/;
const REGEX_HEX_PREFIXED_IGNORE = /^0x[\da-fA-F]+$/;
/**
* @name isHex
* @summary Tests for a hex string.
@@ -22,8 +24,16 @@ export const REGEX_HEX_NOPREFIX = /^([\da-fA-F]{2})+$/;
* isHex('0x1234', 8); // => false
* ```
*/
export function isHex (value: unknown, bitLength = -1): value is HexString {
return (typeof value === 'string' && (value === '0x' || REGEX_HEX_PREFIXED.test(value)))
export function isHex (value: unknown, bitLength = -1, ignoreLength = false): value is HexString {
return (
typeof value === 'string' && (
value === '0x' || (
ignoreLength
? REGEX_HEX_PREFIXED_IGNORE.test(value)
: REGEX_HEX_PREFIXED.test(value)
)
)
)
? bitLength === -1
? true
: (value.length === (2 + Math.ceil(bitLength / 4)))