UNPKG

1.22 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.REGEX_HEX_PREFIXED = exports.REGEX_HEX_NOPREFIX = void 0;
7exports.isHex = isHex;
8// Copyright 2017-2022 @polkadot/util authors & contributors
9// SPDX-License-Identifier: Apache-2.0
10const REGEX_HEX_PREFIXED = /^0x[\da-fA-F]+$/;
11exports.REGEX_HEX_PREFIXED = REGEX_HEX_PREFIXED;
12const REGEX_HEX_NOPREFIX = /^[\da-fA-F]+$/;
13/**
14 * @name isHex
15 * @summary Tests for a hex string.
16 * @description
17 * Checks to see if the input value is a `0x` prefixed hex string. Optionally (`bitLength` !== -1) checks to see if the bitLength is correct.
18 * @example
19 * <BR>
20 *
21 * ```javascript
22 * import { isHex } from '@polkadot/util';
23 *
24 * isHex('0x1234'); // => true
25 * isHex('0x1234', 8); // => false
26 * ```
27 */
28
29exports.REGEX_HEX_NOPREFIX = REGEX_HEX_NOPREFIX;
30
31function isHex(value) {
32 let bitLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;
33 let ignoreLength = arguments.length > 2 ? arguments[2] : undefined;
34 return typeof value === 'string' && (value === '0x' || REGEX_HEX_PREFIXED.test(value)) && (bitLength === -1 ? ignoreLength || value.length % 2 === 0 : value.length === 2 + Math.ceil(bitLength / 4));
35}
\No newline at end of file