Skip to content

Instantly share code, notes, and snippets.

@amosrivera
Last active December 24, 2015 11:19
Show Gist options
  • Save amosrivera/6789801 to your computer and use it in GitHub Desktop.
Save amosrivera/6789801 to your computer and use it in GitHub Desktop.
/*
String Calculator
1- The program can take 0, 1 or 2 numbers and will
return their sum, (for an empty string it will return 0)
for example "" or "1" or "1,2" -> 0, 1, 3
2- Allow the Add method to handle an unknown amount
of numbers
3- Allow the Add method to handle new lines between
numbers(instead of commas). The following input
is ok: "1\n2,3" (will equal 6)
4- Support different delimiters. To change a delimiter
the beginning of the string will contain a separate
line that looks like this: "//[delimiter]\n[numbers...]"
for example "//;\n1;2" should return 3 where the
default delimiter is ";"
*/
var add = function(str){
var delimiters = [",","\n"];
if (str == ""){
return 0;
}
if (str.indexOf("//") == 0){
delimiters.push(str[2]); // add new delimiter
str = str.substr(4); // ignore first 5 characters
}
var numbers = str.split(
new RegExp(delimiters.join("|"))
);
return numbers.reduce(function(total,n){
return total + parseInt(n);
},0);
}
// http://jsfiddle.net/ZAJt4/
test("test_should_return_zero_on_empty_string", function() {
equal(add(""),0);
});
test("test_should_return_self_on_number", function() {
equal(add("1"),1);
equal(add("2"),2);
});
test("test_should_return_sum_on_two_numbers", function() {
equal(add("1,2"),3);
equal(add("3,3"),6);
});
test("test_should_return_sum_on_two_numbers", function() {
equal(add("1,2,3"),6);
equal(add("1,2,3,4"),10);
});
test("test_should_return_sum_on_two_numbers", function() {
equal(add("1\n2"),3);
equal(add("1\n2,3"),6);
});
test("test_should_accept_custom_delimiters", function() {
equal(add("//;\n1;2"),3);
equal(add("//;\n1;2\n3"),6);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment