Last active
March 10, 2018 12:23
-
-
Save Gregoor/f3a616c33211d0f13bb8 to your computer and use it in GitHub Desktop.
Advent of Code - Day 1: Not Quite Lisp
This file contains 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 parseFloor = (str) => { | |
const floorCharFns = { | |
'(': n => n + 1, | |
')': n => n - 1 | |
}; | |
let floor = 0; | |
let error; | |
let firstBasementPos; | |
for (let i = 0; i < str.length; i++) { | |
const char = str[i]; | |
const fn = floorCharFns[char]; | |
if (!fn) { | |
error = `Invalid character ${char} at position ${i + 1}`; | |
} | |
floor = fn(floor); | |
if (floor == -1 && !firstBasementPos) firstBasementPos = i + 1; | |
} | |
return {floor, error, firstBasementPos}; | |
}; | |
const expect = (actual, expected) => { | |
if (actual !== expected) { | |
console.error(`Expected ${expected} got ${actual}`) | |
return false; | |
} | |
return true; | |
}; | |
console.clear(); | |
const tests = [ | |
...[ | |
['(())', 0], | |
['()()', 0], | |
['(((', 3], | |
['(()(()(', 3], | |
['))(((((', 3], | |
['())', -1], | |
['))(', -1], | |
[')))', -3], | |
[')())())', -3], | |
].map(([str, expected]) => { | |
return expect(parseFloor(str).floor, expected); | |
}), | |
[ | |
[')', 1], | |
['()())', 5] | |
].map(([str, expected]) => { | |
return expect(parseFloor(str).firstBasementPos, expected); | |
}) | |
]; | |
if (tests.every(Boolean)) console.log('All tests passed!'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment