Skip to content

Commit 2d0b989

Browse files
committed
use pure-JavaScript version of utf8Encode by default
1 parent 6be5c9c commit 2d0b989

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

src/utils/uf8Encode.ts

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import { prettyByte } from "./prettyByte";
22

3-
const USE_NATIVE_TEXT_ENCODER = typeof TextEncoder !== "undefined";
3+
// USE_TEXT_ENOCDER is opt-in because NodeJS v12's impl is much slower than pure-JavaScript version (i.e. _utf8Encode).
4+
// Set `USE_TEXT_ENOCDER=true` to use TextEncoder.
5+
const USE_TEXT_ENCODER = (process.env.USE_TEXT_ENOCDER === 'true' && typeof TextEncoder !== "undefined");
46

5-
function _utf8Encode(str: string): Array<number> {
7+
function _utf8Encode(str: string): ReadonlyArray<number> {
68
const len = str.length;
79

810
const bytes: Array<number> = [];
@@ -46,12 +48,17 @@ function _utf8Encode(str: string): Array<number> {
4648
return bytes;
4749
}
4850

49-
function createNativeUtf8Encode() {
50-
const encoder = new TextEncoder();
51+
function createUtf8Encode() {
52+
if (USE_TEXT_ENCODER) {
53+
const encoder = new TextEncoder();
5154

52-
return (str: string): Array<number> => {
53-
return Array.from(encoder.encode(str));
54-
};
55+
return (str: string): ReadonlyArray<number> => {
56+
// convert to array to avoid --downlevelIteration on the caller
57+
return Array.from(encoder.encode(str));
58+
};
59+
} else {
60+
return _utf8Encode;
61+
}
5562
}
5663

57-
export const utf8Encode = USE_NATIVE_TEXT_ENCODER ? createNativeUtf8Encode() : _utf8Encode;
64+
export const utf8Encode = createUtf8Encode();

0 commit comments

Comments
 (0)