You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: challenges/functions.md
+14Lines changed: 14 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1169,6 +1169,10 @@ function sum() {
1169
1169
#### Q34
1170
1170
### Design a function which can keep recieving the arguments on each function call and returns the sum when no argument is passed
1171
1171
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
+
1172
1176
```js
1173
1177
// Example
1174
1178
sum(2)(4)(6)(1)(); // 13
@@ -1193,6 +1197,16 @@ function sum(a) {
1193
1197
constsum=a=>b=> b ===undefined? a :sum(a + b);
1194
1198
```
1195
1199
1200
+
```js
1201
+
functionsum(a) {
1202
+
if (typeof a ==='undefined') {
1203
+
returnsum.total;
1204
+
}
1205
+
sum.total= (sum.total??0) + a;
1206
+
return sum;
1207
+
}
1208
+
```
1209
+
1196
1210
###### Notes
1197
1211
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)()`
0 commit comments