diff --git a/source/utilities.js b/source/utilities.js index 4366dee..336faf8 100644 --- a/source/utilities.js +++ b/source/utilities.js @@ -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]), + }; +}