Skip to content

Commit f20fb43

Browse files
committed
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.
1 parent cd9c81c commit f20fb43

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
function sum(a) {
2+
3+
let currentSum = a;
4+
5+
function f(b) {
6+
currentSum += b;
7+
return f;
8+
}
9+
10+
f.toString = function() {
11+
return currentSum;
12+
};
13+
14+
return f;
15+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
function sum(a){
2+
3+
// Your code goes here.
4+
5+
}
6+
7+
/*
8+
sum(1)(2) == 3; // 1 + 2
9+
sum(1)(2)(3) == 6; // 1 + 2 + 3
10+
sum(5)(-1)(2) == 6
11+
sum(6)(-1)(-2)(-3) == 0
12+
sum(0)(1)(2)(3)(4)(5) == 15
13+
*/
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
* Instead of hard-coding a bunch of separate test cases and their solutions,
3+
* this code takes several argument lists, and compares the chain call answer
4+
* you made for "sum()" to a more traditional way of adding the contents of an
5+
* array.
6+
*/
7+
8+
describe("sum", function(){
9+
10+
let testArgumentLists = [
11+
[1, 2],
12+
[5, -1, 2],
13+
[6, -1, -2, -3],
14+
[0, 1, 2, 3, 4, 5],
15+
];
16+
17+
for (let argumentList of testArgumentLists){
18+
19+
it(makeTestCaseName(argumentList), function(){
20+
assert.equal(traditionalSum(argumentList), chainCallSum(argumentList));
21+
});
22+
}
23+
24+
});
25+
26+
27+
function traditionalSum(arr){
28+
return arr.reduce(
29+
function(accumulator, item){
30+
return accumulator + item;
31+
}, 0);
32+
}
33+
34+
function makeTestCaseName(arr){
35+
return `sum${makeChainCallString(arr)} == ${traditionalSum(arr)}`;
36+
}
37+
38+
/* Takes the elements of an array, and puts them in a string where each element
39+
* is enclosed in parentheses. Example:
40+
*
41+
* (["a", "b", "c"]) => "(a)(b)(c)"
42+
*
43+
* Useful for making pretty test case names.
44+
*/
45+
function makeChainCallString(arr){
46+
return arr.reduce(
47+
function(accumulator, item){
48+
return `${accumulator}(${item})`;
49+
}, "");
50+
}
51+
52+
function chainCallSum(arr){
53+
return arr.reduce(
54+
function(accumulator, item){
55+
return accumulator(item);
56+
}, sum);
57+
}

0 commit comments

Comments
 (0)