1 | import { traverse, curry, pipe, prop, curryN } from 'ramda';
|
---|
2 |
|
---|
3 | import Identity from './fantasy-land/Identity';
|
---|
4 |
|
---|
5 | /**
|
---|
6 | * Creates a [Traversable](https://github.com/fantasyland/fantasy-land#traversable) lens
|
---|
7 | * from an [Applicative](https://github.com/fantasyland/fantasy-land#applicative)-returning function.
|
---|
8 | *
|
---|
9 | * When executed, it maps an [Applicative](https://github.com/fantasyland/fantasy-land#applicative)-returning
|
---|
10 | * function over a [Traversable](https://github.com/fantasyland/fantasy-land#traversable),
|
---|
11 | * then uses [`sequence`](https://ramdajs.com/docs/#sequence) to transform the resulting Traversable of Applicative
|
---|
12 | * into an Applicative of Traversable.
|
---|
13 | *
|
---|
14 | * Dispatches to the `traverse` method of the third argument, if present.
|
---|
15 | *
|
---|
16 | * @func lensTraverse
|
---|
17 | * @memberOf RA
|
---|
18 | * @since {@link https://char0n.github.io/ramda-adjunct/2.7.0|2.7.0}
|
---|
19 | * @category Relation
|
---|
20 | * @typedef Lens s a = Functor f => (a -> f a) -> s -> f s
|
---|
21 | * @sig fantasy-land/of :: TypeRep f => f ~> a → f a
|
---|
22 | * @sig Applicative f => (a -> f a) -> Lens s a
|
---|
23 | * @sig Applicative f => TypeRep f -> Lens s a
|
---|
24 | * @param {!Object|!Function} TypeRepresentative with an `of` or `fantasy-land/of` method
|
---|
25 | * @return {!function} The Traversable lens
|
---|
26 | * @see {@link http://ramdajs.com/docs/#lens|R.lens}, {@link http://ramdajs.com/docs/#traverse|R.traverse}
|
---|
27 | *
|
---|
28 | * @example
|
---|
29 | *
|
---|
30 | * const maybeLens = RA.lensTraverse(Maybe.of);
|
---|
31 | * const safeDiv = n => d => d === 0 ? Maybe.Nothing() : Maybe.Just(n / d)
|
---|
32 | *
|
---|
33 | * R.over(maybeLens, safeDiv(10), [2, 4, 5]); // => Just([5, 2.5, 2])
|
---|
34 | * R.over(maybeLens, safeDiv(10), [2, 0, 5]); // => Nothing
|
---|
35 | *
|
---|
36 | * R.view(maybeLens, [Maybe.Just(2), Maybe.Just(3)]); // => Maybe.Just([2, 3])
|
---|
37 | *
|
---|
38 | * R.set(maybeLens, Maybe.Just(1), [Maybe.just(2), Maybe.Just(3)]); // => Maybe.Just([1, 1])
|
---|
39 | */
|
---|
40 | /* eslint-disable no-nested-ternary */
|
---|
41 | const lensTraverse = curryN(1, (F) => {
|
---|
42 | const of =
|
---|
43 | typeof F['fantasy-land/of'] === 'function'
|
---|
44 | ? F['fantasy-land/of']
|
---|
45 | : typeof F.of === 'function'
|
---|
46 | ? F.of
|
---|
47 | : F;
|
---|
48 | const TypeRep = { 'fantasy-land/of': of };
|
---|
49 |
|
---|
50 | return curry((toFunctorFn, target) =>
|
---|
51 | Identity.of(traverse(TypeRep, pipe(toFunctorFn, prop('value')), target))
|
---|
52 | );
|
---|
53 | });
|
---|
54 | /* eslint-enable */
|
---|
55 |
|
---|
56 | export default lensTraverse;
|
---|