stripPrefix adjustment

This commit is contained in:
Jaco
2021-11-17 14:07:43 +02:00
parent e1354746b1
commit 5524e50baf
3 changed files with 26 additions and 6 deletions
+12
View File
@@ -22,9 +22,21 @@ describe('hexStripPrefix', (): void => {
).toEqual('1223');
});
it('strips the prefix from hex strings (non 2 lnegth)', (): void => {
expect(
hexStripPrefix('0x123')
).toEqual('123');
});
it('returns un-prefixed hex as-is', (): void => {
expect(
hexStripPrefix('abcd1223')
).toEqual('abcd1223');
});
it('throws when invalid hex', (): void => {
expect(
() => hexStripPrefix('0x0x01ab')
).toThrow(/Expected hex value to convert/);
});
});
+11 -5
View File
@@ -1,6 +1,8 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { REGEX_HEX_NOPREFIX_IGNORE, REGEX_HEX_PREFIXED_IGNORE } from '../is/hex';
/**
* @name hexStripPrefix
* @summary Strips any leading `0x` prefix.
@@ -16,9 +18,13 @@
* ```
*/
export function hexStripPrefix (value?: string | null): string {
return (!value || value === '0x')
? ''
: value.startsWith('0x')
? value.substr(2)
: value;
if (!value || value === '0x') {
return '';
} else if (REGEX_HEX_PREFIXED_IGNORE.test(value)) {
return value.substr(2);
} else if (REGEX_HEX_NOPREFIX_IGNORE.test(value)) {
return value;
}
throw new Error(`Expected hex value to convert, found '${value}'`);
}
+3 -1
View File
@@ -7,7 +7,9 @@ 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]+$/;
export const REGEX_HEX_PREFIXED_IGNORE = /^0x[\da-fA-F]+$/;
export const REGEX_HEX_NOPREFIX_IGNORE = /^[\da-fA-F]+$/;
/**
* @name isHex