Skip to content

Commit d63f326

Browse files
committed
Isomorphisms and round trip data transformations
1 parent 46af9e8 commit d63f326

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

26.introduction-isomorphism.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
const { Right, Left } = require('./either');
2+
3+
// from(to(x)) === x
4+
// to(from(x)) === x
5+
// String ~ [Char]
6+
const Iso = (to, from) => ({ to, from });
7+
8+
const chars = Iso(s => s.split(''), c => c.join(''));
9+
10+
const helloWorld = 'hello world';
11+
const arrHelloWorld = [ 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd' ];
12+
13+
const res1 = chars.from(chars.to(helloWorld));
14+
const res2 = chars.to(chars.from(arrHelloWorld));
15+
16+
console.log(res1, helloWorld);
17+
console.log(res2, arrHelloWorld);
18+
19+
const truncate = str => chars.from(chars.to(str).slice(0, 3)).concat('...');
20+
21+
const res3 = truncate(helloWorld);
22+
23+
console.log(res3, 'hel...');
24+
25+
// [a] ~ Either || null || a
26+
const singleton = Iso(
27+
e => e.fold(() => [], x => [x]),
28+
([x]) => x ? Right(x) : Left()
29+
);
30+
31+
const filterEither = (e, pred) => singleton.from(singleton.to(e).filter(pred));
32+
33+
const res4 = filterEither(
34+
Right('hello'),
35+
x => x.match(/h/ig)).map(x => x.toUpperCase(x));
36+
37+
console.log(res4);

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
23. [Maintaining structure whilst asyncing](23.maintaining-structure-whilst-asyncing.js)
2828
24. [Principled type conversions with Natural Transformations](24.natural-transformations.js)
2929
25. [Apply Natural Transformations in everyday work](25.everyday-natural-transformations.js)
30+
26. [Isomorphisms and round trip data transformations](26.introduction-isomorphism.js)
3031

3132
## How to run
3233

0 commit comments

Comments
 (0)