TextEncoder/Decoder polyfill optimisation (#286)

This commit is contained in:
Jaco Greeff
2019-01-03 13:52:03 +01:00
committed by GitHub
parent a1c3887b78
commit d47b865df9
2 changed files with 26 additions and 18 deletions
+11 -7
View File
@@ -2,12 +2,20 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
let decoder: TextDecoder | undefined;
let decoder: { decode: (value: Uint8Array) => string };
function polyfilledDecode (value: Uint8Array): string {
return value.reduce((str, code) => {
return str + String.fromCharCode(code);
}, '');
}
try {
decoder = new TextDecoder('utf-8');
} catch (error) {
// ignore
decoder = {
decode: polyfilledDecode
};
}
/**
@@ -28,11 +36,7 @@ try {
export default function u8aToString (value?: Uint8Array): string {
if (!value || !value.length) {
return '';
} else if (decoder) {
return decoder.decode(value);
}
return value.reduce((str, code) => {
return str + String.fromCharCode(code);
}, '');
return decoder.decode(value);
}