Skip to content

Instantly share code, notes, and snippets.

@7jpsan
Last active July 23, 2020 14:34
Show Gist options
  • Select an option

  • Save 7jpsan/c1dc6f7c979b5c4a821d8ac926330e8a to your computer and use it in GitHub Desktop.

Select an option

Save 7jpsan/c1dc6f7c979b5c4a821d8ac926330e8a to your computer and use it in GitHub Desktop.
function replace(template: string, replacements: string[]) {
const initialState = {
result: '',
valid: true,
openGroup: false,
previous: '',
index: 0,
};
return template.split('').reduce((acc, next) => {
if (!acc.valid) {
return acc;
}
switch (next) {
case '{':
if (acc.previous === '{') {
acc.result = `${acc.result}{`;
acc.openGroup = false;
} else {
acc.openGroup = true;
}
break;
case '}':
if (acc.openGroup) {
if (acc.index < replacements.length) {
acc.result = `${acc.result}${replacements[acc.index]}`;
acc.index = 0;
acc.openGroup = false;
} else {
acc.valid = false;
acc.result = '';
}
} else {
acc.result = `${acc.result}}`;
}
break;
default:
if (acc.openGroup) {
if (next.match(/\s/) || isNaN(+next)) {
acc.valid = false;
acc.result = '';
} else {
acc.index = acc.index * 10 + +next;
}
} else {
acc.result = `${acc.result}${next}`;
}
}
acc.previous = next;
return acc;
}, initialState).result;
}
const result = replace('This is a {{ {1} {0} {0}}', ['string', 'number']);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment