您的位置:首页 > 其它

[Compose] Isomorphisms and round trip data transformations

2017-01-23 15:15 295 查看
What is Isomorphisms?
We have a value x, then apply function 'to' and 'from' to value 'x', the result we should still get 'x'.

// from(to(x)) == x
// to(from(y)) == y


So Isomorphisms is kind of opreation able to tranform a value back and forward without lose anything.

Example1:

const Iso = (to, from) => ({
to,
from
})

// String <-> [Chat]
const StoC = Iso(
(str) => str.split(''),
(chat) => chat.join('')
);

const res = StoC.from(StoC.to('How'));


Example2:

// String <-> [Chat]
const StoC = Iso(
(str) => str.split(''),
(chat) => chat.join('')
);

const truncate = (str, num) => StoC.from(StoC.to(str).slice(0,num)).concat('...');
let res = truncate("Hello World!", 7);
console.log(res); // "Hello W..."


Example3:

const Iso = (to, from) => ({
to,
from
})

// [a] <-> Either/null/a
const singleton = Iso(
(either) => either.fold(() => [], x => [x]),
([x]) => x? Right(x): Left()
)

const filterEither = (e, pred) => singleton.from(singleton.to(e).filter(pred));
const res = filterEither(Right('hello'), (x) => x.match(/h/ig))
.map(x => x.toUpperCase());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: