Skip to content

Commit

Permalink
Improve performance of main function (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky authored Mar 24, 2021
1 parent 6acf7d9 commit 9c36efc
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,22 +114,34 @@ if (platform === 'linux') {
// TODO: Use https://github.com/sindresorhus/is-unicode-supported when targeting Node.js 10.
const figures = platform === 'win32' ? fallback : main;

const fn = string => {
const isFallbackFigure = ([key, mainValue]) => figures[key] !== mainValue;
const getFigureRegExp = ([key, mainValue]) => [new RegExp(escapeStringRegexp(mainValue), 'g'), figures[key]];

let replacements = [];
const getReplacements = () => {
if (replacements.length !== 0) {
return replacements;
}

replacements = Object.entries(main)
.filter(isFallbackFigure)
.map(getFigureRegExp);
return replacements;
};

// On Windows, substitute non-fallback to fallback figures
const replaceCharsToFallback = string => {
if (figures === main) {
return string;
}

for (const [key, value] of Object.entries(main)) {
if (value === figures[key]) {
continue;
}

string = string.replace(new RegExp(escapeStringRegexp(value), 'g'), figures[key]);
for (const [mainRegExp, fallbackValue] of getReplacements()) {
string = string.replace(mainRegExp, fallbackValue);
}

return string;
};

module.exports = Object.assign(fn, figures);
module.exports = Object.assign(replaceCharsToFallback, figures);
module.exports.main = main;
module.exports.windows = fallback;

0 comments on commit 9c36efc

Please sign in to comment.