Skip to content

Instantly share code, notes, and snippets.

@amankkg
Created April 14, 2019 13:22
Show Gist options
  • Save amankkg/3f27f401657727fa597a9df15e16e4dc to your computer and use it in GitHub Desktop.
Save amankkg/3f27f401657727fa597a9df15e16e4dc to your computer and use it in GitHub Desktop.
lens usage
import R from 'ramda'
const recordsLens = R.lensPath(['foo', 'records'])
const keysLens = R.lensPath(['bar', 'keys'])
const reducer = (state, {type, payload}) => {
switch (type) {
case 'SET_RECORDS': return R.set(recordsLens, payload, state)
case 'SET_RECORD': {
const exactRecordLens = R.lensPath([payload.id])
const recordLens = R.compose(recordsLens, exactRecordLens)
return R.set(recordLens, payload.value, state)
}
case 'ADD_KEY': return R.over(keysLens, R.append(payload), state)
case 'CLEAR_KEYS': return R.set(keysLens, [], state)
default: return state
}
}
const s0 = {foo: {records: {}}, bar: {keys: []}}
const s1 = reducer(s0, {type: 'SET_RECORDS', payload: {a: 'Aye!', b: 'Boo!'}})//?$.foo
const s2 = reducer(s1, {type: 'SET_RECORD', payload: {id: 'a', value: 'Aight?'}})//?$.foo
const s3 = reducer(s2, {type: 'ADD_KEY', payload: 17})//?$.bar
const s4 = reducer(s3, {type:'ADD_KEY', payload: 42})//?$.bar
const s5 = reducer(s4, {type: 'CLEAR_KEYS'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment