-
Notifications
You must be signed in to change notification settings - Fork 36
Cookbook
Kurt Milam edited this page Jun 14, 2017
·
17 revisions
This page contains a collection of 'recipes', simple examples of partial.lenses-based solutions to common problems.
Convert a structure like this [ { id: 'a', v: 1 }, { id: 'b', v: 2 } ]
to one like this { a: 1, b: 2 }
and back. See it in action on the partial.lenses Playground.
const data = [ { id: 'a', val: 1 }, { id: 'b', val: 2 } ]
const arrayToObjectL = ( keyProp, valProp ) => xs =>
xs.reduce( ( acc, x ) => ( acc[ x[ keyProp ] ] = x[ valProp ], acc ), {} )
const objectToArrayL = ( keyProp, valProp ) => obj =>
Object.keys( obj ).map( x => ( { [ keyProp ]: x, [ valProp ]: obj[ x ] } ) )
const arrayToObjectIsoL = ( keyProp, valProp ) =>
L.iso( arrayToObjectL( keyProp, valProp ), objectToArrayL( keyProp, valProp ) )
const d1 = L.get( arrayToObjectIsoL( 'id', 'val' ), data )
const d2 = L.modify( [ arrayToObjectIsoL( 'id', 'val' ), L.values ], R.inc, data )
R.identity( { d1, d2 } )
// result:
{
"d1": { "a": 1, "b": 2 },
"d2": [ { "id": "a", "val": 2 }, { "id": "b" "val": 3 } ]
}