Skip to content

Commit d5f6478

Browse files
authored
Q34 new solution add
1 parent 1ad7cba commit d5f6478

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

challenges/functions.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1169,6 +1169,10 @@ function sum() {
11691169
#### Q34
11701170
### Design a function which can keep recieving the arguments on each function call and returns the sum when no argument is passed
11711171
1172+
- The function can be designed to return another function which maintains the closure over the previous sum value
1173+
- The check for breaking condition can be added using the argument check for `undefined`
1174+
- 3rd solution uses the property on function to store the total which will be updated on each call hence the same function can be returned
1175+
11721176
```js
11731177
// Example
11741178
sum(2)(4)(6)(1)(); // 13
@@ -1193,6 +1197,16 @@ function sum(a) {
11931197
const sum = a => b => b === undefined ? a : sum(a + b);
11941198
```
11951199
1200+
```js
1201+
function sum(a) {
1202+
if (typeof a === 'undefined') {
1203+
return sum.total;
1204+
}
1205+
sum.total = (sum.total ?? 0) + a;
1206+
return sum;
1207+
}
1208+
```
1209+
11961210
###### Notes
11971211
In the code value is checked if it is undefined reason being 0 is a falsy value and `b ? a : sum(a + b)` code fails when one of the argument is 0. Example: `sum(4)(3)(0)(2)()`
11981212

0 commit comments

Comments
 (0)