Skip to content

Commit b52e6a8

Browse files
committed
Add simple example
1 parent 70e94a7 commit b52e6a8

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

‎JavaScript/1-chain.js‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
'use strict';
2+
3+
class Adder {
4+
constructor(type, reducer) {
5+
this.type = type;
6+
this.reducer = reducer;
7+
this.next = null;
8+
}
9+
}
10+
11+
class Chain {
12+
constructor() {
13+
this.first = null;
14+
this.last = null;
15+
}
16+
17+
add(adder) {
18+
if (!this.first) this.first = adder;
19+
else this.last.next = adder;
20+
this.last = adder;
21+
return this;
22+
}
23+
24+
process(collection) {
25+
let adder = this.first;
26+
do {
27+
if (collection instanceof adder.type) {
28+
return adder.reducer(collection);
29+
}
30+
adder = adder.next;
31+
} while (adder);
32+
throw new Error('Unsupported collection type');
33+
}
34+
}
35+
36+
// Usage
37+
38+
const sum = (a, b) => a + b;
39+
40+
const chain = new Chain()
41+
.add(new Adder(Array, array => array.reduce(sum)))
42+
.add(new Adder(Set, set => [...set].reduce(sum)))
43+
.add(new Adder(Uint8Array, u8a => Array.from(u8a).reduce(sum)))
44+
.add(new Adder(Object, obj => `Not supported ${obj.constructor.name}`));
45+
46+
const sum1 = chain.process([1, 2, 3]);
47+
console.dir({ sum1 });
48+
49+
const sum2 = chain.process(new Set([1, 2, 3]));
50+
console.dir({ sum2 });
51+
52+
const sum3 = chain.process(new Uint8Array([1, 2, 3]));
53+
console.dir({ sum3 });
54+
55+
const sum4 = chain.process(new Int32Array([1, 2, 3]));
56+
console.dir({ sum4 });

0 commit comments

Comments
 (0)