Last active
September 13, 2019 00:34
-
-
Save sebinsua/469410866377fc5af087853b34556b6d 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
| const takeNumber = pattern => { | |
| const [_number] = pattern.match(/^\d+/g) || []; | |
| return parseInt(_number, 10) || 1; | |
| }; | |
| const str = pattern => { | |
| let count = 1; | |
| let parts = ""; | |
| let part = ""; | |
| for (let idx = 0; idx < pattern.length; idx++) { | |
| const char = pattern[idx]; | |
| if (/\d+/.test(char)) { | |
| if (/\d+/.test(pattern[idx - 1]) === false) { | |
| count = takeNumber(pattern.slice(idx)); | |
| } | |
| continue; | |
| } | |
| if (char === "]") { | |
| break; | |
| } else if (char === "[") { | |
| let newPart = str(pattern.slice(idx + 1)); | |
| idx += newPart.length + 1; | |
| part = | |
| part + | |
| Array(count) | |
| .fill(newPart) | |
| .join(""); | |
| count = takeNumber(pattern.slice(idx)); | |
| parts += part; | |
| part = ""; | |
| continue; | |
| } else { | |
| part += char; | |
| } | |
| } | |
| if (part.length) { | |
| parts += part; | |
| } | |
| return parts; | |
| }; | |
| console.log(str("abc")); | |
| console.log(str("3[abc]")); | |
| console.log(str("4[word]2[ab]")); | |
| console.log(str("10[word]")); | |
| console.log(str("2[hey]3[2[b2[c]]")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment