Last active
July 23, 2020 14:34
-
-
Save 7jpsan/c1dc6f7c979b5c4a821d8ac926330e8a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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