Adjust encoder/decoder fallbacks (#750)

* Adjust encoder/decoder fallbacks

* Dep-dup is functions

* Complexity cleanups
This commit is contained in:
Jaco Greeff
2020-11-08 11:20:22 +01:00
committed by GitHub
parent e1aa096cef
commit c67c1966d7
18 changed files with 118 additions and 78 deletions
+3 -11
View File
@@ -1,16 +1,8 @@
// Copyright 2017-2020 @polkadot/x-textencoder authors & contributors
// SPDX-License-Identifier: Apache-2.0
import Fallback from './fallback';
export default typeof TextEncoder === 'undefined'
? class {
encode (value: string): Uint8Array {
const u8a = new Uint8Array(value.length);
for (let i = 0; i < value.length; i++) {
u8a[i] = value.charCodeAt(i);
}
return u8a;
}
}
? Fallback as unknown as typeof TextEncoder
: TextEncoder;
+15
View File
@@ -0,0 +1,15 @@
// Copyright 2017-2020 @polkadot/x-textencoder authors & contributors
// SPDX-License-Identifier: Apache-2.0
// This is very limited, only handling Ascii values
export default class TextEncoder {
encode (value: string): Uint8Array {
const u8a = new Uint8Array(value.length);
for (let i = 0; i < value.length; i++) {
u8a[i] = value.charCodeAt(i);
}
return u8a;
}
}
+16 -14
View File
@@ -3,19 +3,21 @@
import { TextEncoder as NodeTextEncoder } from 'util';
class NodeFallback {
#encoder: NodeTextEncoder;
constructor () {
this.#encoder = new NodeTextEncoder();
}
// For a Jest 26.0.1 environment, Buffer !== Uint8Array
encode (value: string): Uint8Array {
const encoded = this.#encoder.encode(value);
return Uint8Array.from(encoded);
}
}
export default typeof TextEncoder === 'undefined'
? class {
#encoder: NodeTextEncoder;
constructor () {
this.#encoder = new NodeTextEncoder();
}
// For a Jest 26.0.1 environment, Buffer !== Uint8Array
encode (value: string): Uint8Array {
const encoded = this.#encoder.encode(value);
return Uint8Array.from(encoded);
}
} as unknown as typeof TextEncoder
? NodeFallback as unknown as typeof TextEncoder
: TextEncoder;