|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +let _ = require('lodash'); |
| 4 | + |
| 5 | +function getSubstrLength(passedString, passedChars) { |
| 6 | + let string; |
| 7 | + if (passedChars) { |
| 8 | + string = ''; |
| 9 | + let count = 0; |
| 10 | + let cursor = 0; |
| 11 | + while(count < passedChars) { |
| 12 | + let match = passedString.substr(cursor).match(/^(\(\d+x\d+\))/); |
| 13 | + string += passedString[cursor] || ''; |
| 14 | + cursor++; |
| 15 | + count++; |
| 16 | + } |
| 17 | + } |
| 18 | + else { |
| 19 | + string = passedString; |
| 20 | + } |
| 21 | + let output = 0; |
| 22 | + |
| 23 | + let cursor = 0; |
| 24 | + while (cursor < string.length) { |
| 25 | + let match = string.substr(cursor).match(/^\((\d+)x(\d+)\)/); |
| 26 | + if (match) { |
| 27 | + let chars = parseInt(match[1]); |
| 28 | + let repeat = parseInt(match[2]); |
| 29 | + |
| 30 | + let repeater = '(' + match[1] + 'x' + match[2] + ')'; |
| 31 | + let substr = getSubstrLength(string.substr(cursor + repeater.length), chars); |
| 32 | + |
| 33 | + output += substr*repeat; |
| 34 | + |
| 35 | + cursor += (chars + repeater.length); |
| 36 | + } |
| 37 | + else { |
| 38 | + output++; |
| 39 | + cursor++; |
| 40 | + continue; |
| 41 | + } |
| 42 | + } |
| 43 | + return output; |
| 44 | +} |
| 45 | + |
| 46 | +module.exports = [ |
| 47 | + // Challenge 1 |
| 48 | + input => { |
| 49 | + input = input.replace(/\s/g, ''); |
| 50 | + |
| 51 | + let output = ''; |
| 52 | + |
| 53 | + let cursor = 0; |
| 54 | + while (cursor < input.length) { |
| 55 | + let match = input.substr(cursor).match(/^\((\d+)x(\d+)\)/); |
| 56 | + if (match) { |
| 57 | + let chars = parseInt(match[1]); |
| 58 | + let repeat = parseInt(match[2]); |
| 59 | + |
| 60 | + let repeater = '(' + match[1] + 'x' + match[2] + ')'; |
| 61 | + let substr = input.substr(cursor + repeater.length, chars); |
| 62 | + for (let i = 0; i < repeat; ++i) { |
| 63 | + output += substr; |
| 64 | + } |
| 65 | + |
| 66 | + cursor += (chars + repeater.length); |
| 67 | + } |
| 68 | + else { |
| 69 | + output += input[cursor]; |
| 70 | + cursor++; |
| 71 | + continue; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return output.length; |
| 76 | + }, |
| 77 | + |
| 78 | + // Challenge 2 |
| 79 | + input => { |
| 80 | + input = input.replace(/\s/g, ''); |
| 81 | + return getSubstrLength(input, input.length); |
| 82 | + } |
| 83 | + |
| 84 | +]; |
0 commit comments