-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path26.introduction-isomorphism.js
More file actions
37 lines (25 loc) · 945 Bytes
/
26.introduction-isomorphism.js
File metadata and controls
37 lines (25 loc) · 945 Bytes
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
const { Right, Left } = require('./either');
// from(to(x)) === x
// to(from(x)) === x
// String ~ [Char]
const Iso = (to, from) => ({ to, from });
const chars = Iso(s => s.split(''), c => c.join(''));
const helloWorld = 'hello world';
const arrHelloWorld = [ 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd' ];
const res1 = chars.from(chars.to(helloWorld));
const res2 = chars.to(chars.from(arrHelloWorld));
console.log(res1, helloWorld);
console.log(res2, arrHelloWorld);
const truncate = str => chars.from(chars.to(str).slice(0, 3)).concat('...');
const res3 = truncate(helloWorld);
console.log(res3, 'hel...');
// [a] ~ Either || null || a
const singleton = Iso(
e => e.fold(() => [], x => [x]),
([x]) => x ? Right(x) : Left()
);
const filterEither = (e, pred) => singleton.from(singleton.to(e).filter(pred));
const res4 = filterEither(
Right('hello'),
x => x.match(/h/ig)).map(x => x.toUpperCase(x));
console.log(res4);