@nidomiro/relation-tuple-parser
Version:
[](https://www.npmjs.com/package/@nidomiro/relation-tuple-parser)
56 lines • 2.37 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateReplacerFunction = void 0;
const lodash_1 = require("lodash");
function findReplacementsInString(str, possibleReplacements) {
const regexStr = `(${Array.from(possibleReplacements.values()).join('|')})`;
const regex = new RegExp(regexStr, 'g');
return Array.from(str.matchAll(regex)).flatMap((x) => {
if (x.index == null) {
return [];
}
const value = x.values().next().value;
return [
{
start: x.index,
endExcl: x.index + value.length,
prop: possibleReplacements.getByValue(value),
},
];
});
}
function generateReplacerFunctions(sortedFoundReplacements, str) {
const resultStringParts = [];
let pos = 0;
sortedFoundReplacements.forEach(({ start, endExcl, prop }) => {
const strPart = str.substring(pos, Math.max(0, start)); // let calculation happen before
resultStringParts.push(() => strPart);
resultStringParts.push((replacements) => String((0, lodash_1.get)(replacements, prop)));
pos = endExcl;
});
if (pos < str.length) {
const strPart = str.substring(pos, str.length);
resultStringParts.push(() => strPart);
}
return resultStringParts;
}
const generateReplacerFunction = (str, possibleReplacements) => {
const foundReplacements = findReplacementsInString(str, possibleReplacements);
const hasNoReplacements = foundReplacements.length === 0;
const isWholeStringReplacement = foundReplacements.length === 1 &&
foundReplacements[0].start === 0 &&
foundReplacements[0].endExcl === str.length;
if (hasNoReplacements) {
return () => str;
}
else if (isWholeStringReplacement) {
return (replacements) => String((0, lodash_1.get)(replacements, foundReplacements[0].prop));
}
const foundReplacementsSortedByStartIndexASC = foundReplacements.sort((a, b) => a.start - b.start);
const resultStringParts = generateReplacerFunctions(foundReplacementsSortedByStartIndexASC, str);
return (replacements) => {
return resultStringParts.map((x) => x(replacements)).join('');
};
};
exports.generateReplacerFunction = generateReplacerFunction;
//# sourceMappingURL=generate-replacer-function.js.map