Skip to content

Instantly share code, notes, and snippets.

@sergey-shpak
Last active May 25, 2019 13:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergey-shpak/9bcdef37003f690f9d6a121f2bb61531 to your computer and use it in GitHub Desktop.
Save sergey-shpak/9bcdef37003f690f9d6a121f2bb61531 to your computer and use it in GitHub Desktop.
Hyperapp V2 actions state lens
/*
This is variation of `squirrel` and `namespace` approaches
https://gist.github.com/zaceno/0d7c62be81a845857e755c1378b7dbff
https://gist.github.com/sergey-shpak/5817bf146cb970bc4e259aef71b89ef4
Simplifies Hyperapp#v2 actions work with deeply nested state
(updated to support returned actions, parameterized actions)
Usage examples:
```
const actions = {
update: (property, value) => value
}
export default {
update: lens(['deeply','nested','property'], actions.update)
}
```
and then call the action
```
import actions from './path/to/actions'
<div onClick={[ actions.update, "new value" ]} />
```
*/
export const lens = (path, cb) =>
path.reduceRight((fn, key) => (obj, ...args) => {
const result = fn(obj[key], ...args)
return (Array.isArray(result) || typeof result == 'function')
? result : { ...obj, [key]: result }
}, cb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment