source: node_modules/ramda-adjunct/src/lensIso.js

main
Last change on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 1.6 KB
Line 
1import { curry, map } from 'ramda';
2
3// This implementation was highly inspired by the implementations
4// in ramda-lens library.
5//
6// https://github.com/ramda/ramda-lens
7
8// isomorphic :: ((a -> b), (b -> a)) -> Isomorphism
9// Isomorphism = x -> y
10const isomorphic = (to, from) => {
11 const isomorphism = (x) => to(x);
12 isomorphism.from = from;
13 return isomorphism;
14};
15
16// isomorphisms :: ((a -> b), (b -> a)) -> (a -> b)
17const isomorphisms = (to, from) =>
18 isomorphic(
19 curry((toFunctorFn, target) => map(from, toFunctorFn(to(target)))),
20 curry((toFunctorFn, target) => map(to, toFunctorFn(from(target))))
21 );
22
23// from :: Isomorphism -> a -> b
24const from = curry((isomorphism, x) => isomorphism.from(x));
25
26/**
27 * Defines an isomorphism that will work like a lens. It takes two functions.
28 * The function that converts and the function that recovers.
29 *
30 * @func lensIso
31 * @memberOf RA
32 * @since {@link https://char0n.github.io/ramda-adjunct/1.19.0|1.19.0}
33 * @category Relation
34 * @typedef Lens s a = Functor f => (a -> f a) -> s -> f s
35 * @sig (s -> a) -> (a -> s) -> Lens s a
36 * @param {!function} to The function that converts
37 * @param {!function} from The function that recovers
38 * @return {!function} The isomorphic lens
39 * @see {@link http://ramdajs.com/docs/#lens|R.lens}
40 *
41 * @example
42 *
43 * const lensJSON = RA.lensIso(JSON.parse, JSON.stringify);
44 *
45 * R.over(lensJSON, assoc('b', 2), '{"a":1}'); //=> '{"a":1,"b":2}'
46 * R.over(RA.lensIso.from(lensJSON), R.replace('}', ',"b":2}'), { a: 1 }); // => { a: 1, b: 2 }
47 */
48const lensIso = curry(isomorphisms);
49lensIso.from = from;
50
51export default lensIso;
Note: See TracBrowser for help on using the repository browser.