Add isAscii (#629)
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
// Copyright 2017-2020 @polkadot/util authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { isAscii } from '.';
|
||||
|
||||
describe('isAscii', (): void => {
|
||||
it('returns true for an ASCII string', (): void => {
|
||||
expect(isAscii('Hello\tWorld!\n\rTesting')).toEqual(true);
|
||||
});
|
||||
|
||||
it('returns true for ASCII bytes', (): void => {
|
||||
expect(isAscii(new Uint8Array([0x31, 0x32, 0x20, 10]))).toEqual(true);
|
||||
});
|
||||
|
||||
it('returns true for empty string inputs', (): void => {
|
||||
expect(isAscii('')).toEqual(true);
|
||||
});
|
||||
|
||||
it('returns true for empty U8a inputs', (): void => {
|
||||
expect(isAscii(new Uint8Array())).toEqual(true);
|
||||
});
|
||||
|
||||
it('returns false for empty undefined inputs', (): void => {
|
||||
expect(isAscii()).toEqual(false);
|
||||
});
|
||||
|
||||
it('returns false for non-printable characters', (): void => {
|
||||
expect(isAscii(new Uint8Array([5]))).toEqual(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright 2017-2020 @polkadot/util authors & contributors
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import u8aToU8a from '../u8a/toU8a';
|
||||
import isString from './string';
|
||||
|
||||
const FORMAT = [9, 10, 13];
|
||||
|
||||
/**
|
||||
* @name isAscii
|
||||
* @summary Tests if the input is printable ASCII
|
||||
* @description
|
||||
* Checks to see if the input string or Uint8Array is printable ASCII, 32-127 + formatters
|
||||
*/
|
||||
export default function isAscii (value?: number[] | Buffer | Uint8Array | string | null): boolean {
|
||||
if (!value) {
|
||||
return isString(value);
|
||||
}
|
||||
|
||||
const u8a = u8aToU8a(value);
|
||||
|
||||
return !u8a.some((byte) => (byte >= 127) || (byte < 32 && !FORMAT.includes(byte)));
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
/**
|
||||
* @summary Type checking utilities
|
||||
*/
|
||||
export { default as isAscii } from './ascii';
|
||||
export { default as isBigInt } from './bigInt';
|
||||
export { default as isBn } from './bn';
|
||||
export { default as isBuffer } from './buffer';
|
||||
|
||||
Reference in New Issue
Block a user