User template string type for isHex (#1020)

* User template string type for isHex

* isHex/isString combo checks
This commit is contained in:
Jaco
2021-06-22 16:05:14 +02:00
committed by GitHub
parent 7d09f0892a
commit 0ef761e899
5 changed files with 16 additions and 22 deletions
+6 -11
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { isString } from './string';
const HEX_REGEX = /^0x[a-fA-F0-9]+$/;
/**
@@ -20,13 +18,10 @@ const HEX_REGEX = /^0x[a-fA-F0-9]+$/;
* isHex('0x1234', 8); // => false
* ```
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function isHex (value: unknown, bitLength = -1, ignoreLength = false): value is string | String {
const isValidHex = value === '0x' || (isString(value) && HEX_REGEX.test(value.toString()));
if (isValidHex && bitLength !== -1) {
return (value as string).length === (2 + Math.ceil(bitLength / 4));
}
return isValidHex && (ignoreLength || ((value as string).length % 2 === 0));
export function isHex (value: unknown, bitLength = -1, ignoreLength = false): value is `0x${string}` {
return (typeof value === 'string' && (value === '0x' || HEX_REGEX.test(value)))
? bitLength === -1
? ((value.length % 2 === 0) || ignoreLength)
: (value.length === (2 + Math.ceil(bitLength / 4)))
: false;
}