Add test case/sandbox for 1-js/06-advanced-functions/06-function-object/5-sum-many-brackets

I used the solution and examples already in the article.
I chose to make the test cases use Array.reduce() to compute the sum,
instead of hard-coding the answer myself.
Not sure how good of practice that is.
This commit is contained in:
Logan Schelly 2020-06-10 15:28:20 -06:00
parent cd9c81cb79
commit f20fb43f70
3 changed files with 85 additions and 0 deletions

View file

@ -0,0 +1,15 @@
function sum(a) {
let currentSum = a;
function f(b) {
currentSum += b;
return f;
}
f.toString = function() {
return currentSum;
};
return f;
}

View file

@ -0,0 +1,13 @@
function sum(a){
// Your code goes here.
}
/*
sum(1)(2) == 3; // 1 + 2
sum(1)(2)(3) == 6; // 1 + 2 + 3
sum(5)(-1)(2) == 6
sum(6)(-1)(-2)(-3) == 0
sum(0)(1)(2)(3)(4)(5) == 15
*/

View file

@ -0,0 +1,57 @@
/*
* Instead of hard-coding a bunch of separate test cases and their solutions,
* this code takes several argument lists, and compares the chain call answer
* you made for "sum()" to a more traditional way of adding the contents of an
* array.
*/
describe("sum", function(){
let testArgumentLists = [
[1, 2],
[5, -1, 2],
[6, -1, -2, -3],
[0, 1, 2, 3, 4, 5],
];
for (let argumentList of testArgumentLists){
it(makeTestCaseName(argumentList), function(){
assert.equal(traditionalSum(argumentList), chainCallSum(argumentList));
});
}
});
function traditionalSum(arr){
return arr.reduce(
function(accumulator, item){
return accumulator + item;
}, 0);
}
function makeTestCaseName(arr){
return `sum${makeChainCallString(arr)} == ${traditionalSum(arr)}`;
}
/* Takes the elements of an array, and puts them in a string where each element
* is enclosed in parentheses. Example:
*
* (["a", "b", "c"]) => "(a)(b)(c)"
*
* Useful for making pretty test case names.
*/
function makeChainCallString(arr){
return arr.reduce(
function(accumulator, item){
return `${accumulator}(${item})`;
}, "");
}
function chainCallSum(arr){
return arr.reduce(
function(accumulator, item){
return accumulator(item);
}, sum);
}