Optimize isAsicc check (#1553)

This commit is contained in:
Jaco
2022-06-20 13:15:00 +03:00
committed by GitHub
parent db0581c051
commit b42ead28e5
2 changed files with 9 additions and 5 deletions
+3 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { stringToU8a } from '../string';
import { perf } from '../test/performance';
import { isAscii } from '.';
@@ -37,5 +38,6 @@ describe('isAscii', (): void => {
expect(isAscii('0x010203')).toEqual(false);
});
perf('isAscii', 100_000, [[[0x31, 0x32, 0x20, 10, 9, 13, 65, 66, 67, 68, 69, 70]]], isAscii);
perf('isAscii (str)', 2_000_000, [['Hello\tWorld!\n\rTesting']], isAscii);
perf('isAscii (u8a)', 200_000, [[[stringToU8a('Hello\tWorld!\n\rTesting')]]], isAscii);
});
+6 -4
View File
@@ -24,7 +24,7 @@ function isAsciiStr (str: AnyString): boolean {
}
/** @internal */
function isAsciiU8a (u8a: Uint8Array): boolean {
function isAsciiBytes (u8a: Uint8Array | Buffer | number[]): boolean {
const count = u8a.length;
for (let i = 0; i < count; i++) {
@@ -46,9 +46,11 @@ function isAsciiU8a (u8a: Uint8Array): boolean {
* Checks to see if the input string or Uint8Array is printable ASCII, 32-127 + formatters
*/
export function isAscii (value?: U8aLike | null): boolean {
return isString(value) && !isHex(value)
? isAsciiStr(value)
return isString(value)
? isHex(value)
? isAsciiBytes(u8aToU8a(value))
: isAsciiStr(value)
: value
? isAsciiU8a(u8aToU8a(value))
? isAsciiBytes(value)
: false;
}