diff --git a/src/randomization.mjs b/src/randomization.mjs index 3629c45c..ab7019c7 100644 --- a/src/randomization.mjs +++ b/src/randomization.mjs @@ -2,6 +2,29 @@ import pkg from './routes.mjs'; import { existsSync, readFileSync } from 'fs'; const { cookingInserts, vegetables, charRandom, splashRandom, cacheBustList, text404 } = pkg; +/* +// Try this instead of the .replace method. Might be more performant. +// Will edit str by replacing all matches of lis with newText. +// Usage: insertText(["", ""], +// " Big Giant Paragraph Smol Paragraph", +// stringOrFunctionToGenerateNewText); +*/ +const insertText = (lis, str, newText) => { +// The lis argument should be a list of strings containing placeholders. +// This will put other relevant argument types, like a string, into a list. + lis = [].concat(lis); + +// Loop through each of the placeholder strings. + for (let i = lis.length - 1, position; i >= 0; i--) { +// Find all matches of a placeholder string and insert new text there. + while ((position = str.indexOf(lis[i])) >= 0) + str = str.slice(0, position) + + (typeof newText == "function" ? newText() : newText) + + str.slice(position + lis[i].length); + } + return str; +}; + function randomListItem(lis) { return lis[Math.floor(Math.random() * lis.length)]; }