Created
February 11, 2015 18:56
-
-
Save Olsenius/5c32bd72f92029839dd8 to your computer and use it in GitHub Desktop.
string calculator kata
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
var assert = require('chai').assert; | |
function findDelimiter (numbers) { | |
var parseDelim = numbers.match(/\/\/(.*),/); | |
if (!parseDelim) { | |
return ","; | |
} | |
return parseDelim[1]; | |
} | |
function normalizeDelimiter (numbers) { | |
numbers = numbers.replace('\n', ','); | |
var delim = findDelimiter(numbers); | |
return numbers | |
.replace('//' + delim + ",", "") | |
.replace(delim, ','); | |
} | |
function detectNegatives (numbers) { | |
return numbers.filter(function(x) { | |
return x < 0; | |
}); | |
} | |
var add = function(numbers){ | |
var parseNums = function(x) { return parseInt(x) || 0; } | |
var sum = function(sum, current) { return sum + current; }; | |
var parsed = normalizeDelimiter(numbers) | |
.split(',') | |
.map(parseNums); | |
var negatives = detectNegatives(parsed); | |
if (negatives.length) { | |
throw new Error("Negative numbers: " + negatives.join(',')); | |
} | |
return parsed.reduce(sum, 0); | |
}; | |
console.log("Running tests", new Date() ); | |
assert.equal(add(""), 0, "empty string"); | |
assert.equal(add("1"), 1, "one"); | |
assert.equal(add("1,2"), 3, "2 numbers"); | |
assert.equal(add("1,2,3,4"), 10, "multiple numbers"); | |
assert.equal(add("1,2,3\n4"), 10, "newline"); | |
assert.equal(add("//;\n1;2"), 3, "custom delimiter"); | |
assert.equal(add("//asd\n1asd2"), 3, "custom delimiter"); | |
assert.throws(function() { add("-1"); }, | |
Error, | |
"Negative numbers: -1", | |
"Detect 1 negative"); | |
assert.throws(function() { add("-1,-2"); }, | |
Error, | |
"Negative numbers: -1,-2", | |
"Detect 2 negatives"); | |
console.log('Done'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment