Skip to content

Commit 9c36efc

Browse files
authoredMar 24, 2021
Improve performance of main function (#49)
1 parent 6acf7d9 commit 9c36efc

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed
 

‎index.js

+20-8
Original file line numberDiff line numberDiff line change
@@ -114,22 +114,34 @@ if (platform === 'linux') {
114114
// TODO: Use https://github.com/sindresorhus/is-unicode-supported when targeting Node.js 10.
115115
const figures = platform === 'win32' ? fallback : main;
116116

117-
const fn = string => {
117+
const isFallbackFigure = ([key, mainValue]) => figures[key] !== mainValue;
118+
const getFigureRegExp = ([key, mainValue]) => [new RegExp(escapeStringRegexp(mainValue), 'g'), figures[key]];
119+
120+
let replacements = [];
121+
const getReplacements = () => {
122+
if (replacements.length !== 0) {
123+
return replacements;
124+
}
125+
126+
replacements = Object.entries(main)
127+
.filter(isFallbackFigure)
128+
.map(getFigureRegExp);
129+
return replacements;
130+
};
131+
132+
// On Windows, substitute non-fallback to fallback figures
133+
const replaceCharsToFallback = string => {
118134
if (figures === main) {
119135
return string;
120136
}
121137

122-
for (const [key, value] of Object.entries(main)) {
123-
if (value === figures[key]) {
124-
continue;
125-
}
126-
127-
string = string.replace(new RegExp(escapeStringRegexp(value), 'g'), figures[key]);
138+
for (const [mainRegExp, fallbackValue] of getReplacements()) {
139+
string = string.replace(mainRegExp, fallbackValue);
128140
}
129141

130142
return string;
131143
};
132144

133-
module.exports = Object.assign(fn, figures);
145+
module.exports = Object.assign(replaceCharsToFallback, figures);
134146
module.exports.main = main;
135147
module.exports.windows = fallback;

0 commit comments

Comments
 (0)