fix: check version and use built in replace all

This commit is contained in:
or orsatti 2025-09-09 10:11:50 +03:00
parent 51557784b8
commit c8ce91527f
No known key found for this signature in database
GPG key ID: CA5E90A8C40B29CE

View file

@ -1,5 +1,17 @@
// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
const SUPPORTED_NODE_VER = 16;
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) {
let index = string.indexOf(substring);
if (index === -1) {
return string;
@ -7,7 +19,7 @@ export function stringReplaceAll(string, substring, replacer) {
const substringLength = substring.length;
let endIndex = 0;
let returnValue = '';
let returnValue = "";
do {
returnValue += string.slice(endIndex, index) + substring + replacer;
endIndex = index + substringLength;
@ -20,14 +32,33 @@ export function stringReplaceAll(string, substring, replacer) {
export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
let endIndex = 0;
let returnValue = '';
let returnValue = "";
do {
const gotCR = string[index - 1] === '\r';
returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
const gotCR = string[index - 1] === "\r";
returnValue +=
string.slice(endIndex, gotCR ? index - 1 : index) +
prefix +
(gotCR ? "\r\n" : "\n") +
postfix;
endIndex = index + 1;
index = string.indexOf('\n', endIndex);
index = string.indexOf("\n", endIndex);
} while (index !== -1);
returnValue += string.slice(endIndex);
return returnValue;
}
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]),
};
}