Created
August 14, 2019 14:31
-
-
Save votemike/23fde2dae452db3e3fa9921682ca66b3 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 add(string) { | |
if (!string) { | |
return 0; | |
} | |
let delimiter = /[\n,]+/; | |
if (string.startsWith('//[')) { | |
const lines = string.split('\n'); | |
delimiter = lines[0].replace(/\/\/\[|\]/g, ''); | |
// const things = lines[0].replace('//', ''); | |
// const delimiters = things.match(/\[(.*?)\]/g); // Can't quite nail the regex on this one | |
// console.log(delimiters); | |
// delimiter = new RegExp(delimiters.join('|')); | |
lines.shift(); | |
string = lines.join('\n'); | |
} | |
const numbers = string.split(delimiter); | |
const negatives = numbers.filter((number) => number < 0); | |
if (negatives.length) { | |
throw (`Negatives not allowed: ${negatives.join(',')}`); | |
} | |
return numbers.reduce((a, b) => { | |
a = a > 1000 ? 0 : a; | |
b = b > 1000 ? 0 : b; | |
return parseInt(a) + parseInt(b); | |
}, 0); | |
} | |
function tests() { | |
test(add(''), 0); | |
test(add('1'), 1); | |
test(add('2'), 2); | |
test(add('1,2'), 3); | |
test(add('1,3'), 4); | |
test(add('2,3'), 5); | |
test(add('2,3,4'), 9); | |
test(add('2,3,4,5'), 14); | |
test(add('2,3,4\n6'), 15); | |
test(add('//[;]\n2;3;4;7'), 16); | |
// test for negatives | |
test(add('2,1001'), 2); | |
test(add('1001,2'), 2); | |
test(add('//[***]\n1***2***3'), 6); | |
test(add('//[*%*]\n1*%*2*%*3'), 6); | |
// test(add('//[***][%%%]\n1%%%2***5'), 8); // Can't quite nail the regex on this one | |
console.log('All tests pass'); | |
} | |
function test(actual, expectation) { | |
if (expectation !== actual) { | |
throw (`${actual} does not equal ${expectation}`); | |
} | |
} | |
tests(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment