Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of main function #49

Merged
merged 2 commits into from
Mar 24, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,22 +135,32 @@ 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 => {
if (figures === main) {
return string;
const isFallbackFigure = ([key, mainValue]) => figures[key] !== mainValue;
const getFigureRegExp = ([key, mainValue]) => [figures[key], new RegExp(escapeStringRegexp(mainValue), 'g')];

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

for (const [key, value] of Object.entries(main)) {
if (value === figures[key]) {
continue;
}
replacements = Object.entries(main)
.filter(isFallbackFigure)
.map(getFigureRegExp);
return replacements;
};

string = string.replace(new RegExp(escapeStringRegexp(value), 'g'), figures[key]);
const replaceCharToFallback = (string, [fallbackValue, mainRegExp]) => string.replace(mainRegExp, fallbackValue);

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

return string;
return getReplacements().reduce(replaceCharToFallback, string);
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved
};

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