Skip to content

Commit 1c36ec3

Browse files
committed
Adder implementation with closures
1 parent 480d217 commit 1c36ec3

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

JavaScript/8-adder.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
'use strict';
2+
3+
const adder = (a) => {
4+
const value = () => a;
5+
const add = (b) => adder(a + b);
6+
return { add, value };
7+
};
8+
9+
const v = adder(3).add(-9).add(12).value();
10+
console.log(v);

JavaScript/9-adder-on.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
'use strict';
2+
3+
const adder = (a) => {
4+
let onZerro = null;
5+
const obj = {};
6+
const value = () => a;
7+
const add = (b) => {
8+
let x = a + b;
9+
if (x < 0) {
10+
x = 0;
11+
if (onZerro) onZerro();
12+
}
13+
return adder(x);
14+
};
15+
const on = (name, callback) => {
16+
if (name === 'zero') onZerro = callback;
17+
return obj;
18+
};
19+
return Object.assign(obj, { add, value, on });
20+
};
21+
22+
const a = adder(3)
23+
.add(-9)
24+
.on('zero', () => console.log('Less than zero'))
25+
.add(12)
26+
.add(5)
27+
.value();
28+
console.log(a);

0 commit comments

Comments
 (0)