Adjust instanceof checks (#1500)

This commit is contained in:
Jaco
2022-05-24 17:56:01 +03:00
committed by GitHub
parent d2b7e88060
commit 51763d3bf9
4 changed files with 23 additions and 3 deletions
+4 -1
View File
@@ -16,5 +16,8 @@
* ```
*/
export function isError (value: unknown): value is Error {
return value instanceof Error;
return (
((value && (value as Record<string, unknown>).constructor) === Error) ||
value instanceof Error
);
}
+4 -1
View File
@@ -17,5 +17,8 @@
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function isInstanceOf (value: unknown, clazz: Function): boolean {
return value instanceof clazz;
return (
((value && (value as Record<string, unknown>).constructor) === clazz) ||
value instanceof Uint8Array
);
}
+9
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { performance } from '../test/performance';
import { isU8a } from '.';
describe('isU8a', (): void => {
@@ -10,6 +11,12 @@ describe('isU8a', (): void => {
).toEqual(false);
});
it('returns false on null values', (): void => {
expect(
isU8a(null)
).toEqual(false);
});
it('returns false on Array values', (): void => {
expect(
isU8a([1, 2, 3])
@@ -28,4 +35,6 @@ describe('isU8a', (): void => {
isU8a(new Uint8Array())
).toEqual(true);
});
performance('isU8a', 2_000_000, [[new Uint8Array()]], isU8a);
});
+6 -1
View File
@@ -16,5 +16,10 @@
* ```
*/
export function isU8a (value?: unknown): value is Uint8Array {
return value instanceof Uint8Array;
// here we defer the instanceof check which is actually slightly
// slower than just checking the constrctor (direct instances)
return (
((value && (value as Record<string, unknown>).constructor) === Uint8Array) ||
value instanceof Uint8Array
);
}