Last active
August 24, 2017 12:18
-
-
Save jozsefs/2497d3fd693cb70cd3dfc80be0ef3ffd to your computer and use it in GitHub Desktop.
alphabet-wars.js
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 alphabetWar(battlefield) { | |
| const remaining = []; | |
| const splitStr = battlefield.split(/(\[[^\]]*\])/g); | |
| const hasNuke = battlefield.indexOf('#') > -1; | |
| splitStr.forEach((item, idx) => { | |
| const isInShelter = item.indexOf('[') === 0; | |
| // the whole thing was put together in like 20 minutes #ripReadability | |
| if (!hasNuke || isInShelter && ( | |
| !(idx > 0 && /([#][^#]*){2}/.test(splitStr[idx - 1])) && | |
| !(idx < splitStr.length - 1 && /([#][^#]*){2}/.test(splitStr[idx + 1])) && | |
| !(idx > 0 && idx < splitStr.length - 1 && splitStr[idx - 1].indexOf('#') > -1 && splitStr[idx + 1].indexOf('#') > -1) | |
| ) | |
| ) { | |
| if (isInShelter) { | |
| item = item.slice(1, -1); | |
| } | |
| item.split('').forEach(letter => remaining.push(letter)); | |
| } | |
| }); | |
| return remaining.join(''); | |
| } | |
| // just to run tests from codewars | |
| Test = { | |
| assertEquals(a, b) { | |
| if (a === b) { | |
| console.log('Test passed'); | |
| } | |
| else { | |
| console.log(`Test failed, expected: ${b}, got: ${a}`); | |
| } | |
| } | |
| }; | |
| Test.assertEquals(alphabetWar('abde[fgh]ijk'), 'abdefghijk'); | |
| Test.assertEquals(alphabetWar('ab#de[fgh]ijk'), 'fgh'); | |
| Test.assertEquals(alphabetWar('ab#de[fgh]ij#k'), ''); | |
| Test.assertEquals(alphabetWar('##abde[fgh]ijk'), ''); | |
| Test.assertEquals(alphabetWar('##abde[fgh]'), ''); | |
| Test.assertEquals(alphabetWar('##abcde[fgh]'), ''); | |
| Test.assertEquals(alphabetWar('abcde[fgh]'), 'abcdefgh'); | |
| Test.assertEquals(alphabetWar('##abde[fgh]ijk[mn]op'), 'mn'); | |
| Test.assertEquals(alphabetWar('#abde[fgh]i#jk[mn]op'), 'mn'); | |
| Test.assertEquals(alphabetWar('[ab]adfd[dd]##[abe]dedf[ijk]d#d[h]#'), 'abijk'); | |
| Test.assertEquals(alphabetWar('[a]#[b]#[c]'), 'ac'); | |
| Test.assertEquals(alphabetWar('[a]#b#[c][d]'),'d'); | |
| Test.assertEquals(alphabetWar('[a][b][c]'), 'abc'); | |
| Test.assertEquals(alphabetWar('##a[a]b[c]#'),'c'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment