-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchain_adding_function.js
More file actions
59 lines (44 loc) · 1.25 KB
/
chain_adding_function.js
File metadata and controls
59 lines (44 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
function add(n) {
// Let the currying begin!
const self = function(m) {
return add(n + m);
};
self.valueOf = function() {
return n;
};
return self;
}
add(1);
//* Updated */
function add(n) {
// Let the currying begin!
// This inner function captures 'n' in its closure
const self = function(m) {
// When called, it returns a NEW instance of add with the updated sum
return add(n + m);
};
// This overrides the default object-to-primitive conversion
// It allows 'add(1)(2)' to be treated as a number in math operations
self.valueOf = function() {
return n;
};
return self;
}
/*
Modern Refactor with Arrow Functions.
Symbol.toPrimitive instead of valueOf.
Symbol.toPrimitive is the ES6+ standard for defining how an object should behave when converted to a string or number.
*/
/**
* A curried addition function that supports infinite chaining.
* Follows the DRY principle by reusing the same logic recursively.
*/
const add = (n) => {
// Recursively return the add function with the accumulated sum
const fn = (m) => add(n + m);
// Define how the function behaves when used as a value (e.g., +add(1)(2))
fn[Symbol.toPrimitive] = (hint) => n;
return fn;
};
// Usage:
// console.log(+add(1)(2)(3)); // 6