chalk/source/utilities.js

65 lines
1.5 KiB
JavaScript
Raw Normal View History

const SUPPORTED_NODE_VER = 16;
2021-04-16 15:23:29 +07:00
export function stringReplaceAll(string, substring, replacer) {
if (
getVersion()?.major >= SUPPORTED_NODE_VER
typeof String.prototype.replaceAll === "function" &&
) {
return string.replaceAll(substring, replacer);
}
return _stringReplaceAllPolyfill(string, substring, replacer);
}
function _stringReplaceAllPolyfill(string, substring, replacer) {
2019-07-12 09:40:23 +03:00
let index = string.indexOf(substring);
if (index === -1) {
return string;
}
2019-07-12 13:59:50 +07:00
const substringLength = substring.length;
let endIndex = 0;
let returnValue = "";
2019-07-12 09:40:23 +03:00
do {
returnValue += string.slice(endIndex, index) + substring + replacer;
2019-07-12 13:59:50 +07:00
endIndex = index + substringLength;
index = string.indexOf(substring, endIndex);
2019-07-12 09:40:23 +03:00
} while (index !== -1);
2021-04-16 15:23:29 +07:00
returnValue += string.slice(endIndex);
2019-07-12 13:59:50 +07:00
return returnValue;
2021-04-16 15:23:29 +07:00
}
2019-07-12 09:40:23 +03:00
2021-04-16 15:23:29 +07:00
export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
2019-07-12 13:59:50 +07:00
let endIndex = 0;
let returnValue = "";
2019-07-12 09:40:23 +03:00
do {
const gotCR = string[index - 1] === "\r";
returnValue +=
string.slice(endIndex, gotCR ? index - 1 : index) +
prefix +
(gotCR ? "\r\n" : "\n") +
postfix;
2019-07-12 13:59:50 +07:00
endIndex = index + 1;
index = string.indexOf("\n", endIndex);
2019-07-12 09:40:23 +03:00
} while (index !== -1);
2021-04-16 15:23:29 +07:00
returnValue += string.slice(endIndex);
2019-07-12 13:59:50 +07:00
return returnValue;
2021-04-16 15:23:29 +07:00
}
function getVersion() {
const nodeVersion = process.version;
if (!nodeVersion) {
return null;
}
const parts = nodeVersion.split(".");
return {
major: parseInt(parts[0]),
minor: parseInt(parts[1]),
patch: parseInt(parts[2]),
};
}