Created
July 28, 2016 22:07
-
-
Save michaelmesser/eda43d43499519aca4adca6cc4ba6dcb to your computer and use it in GitHub Desktop.
Ramda lens helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const blankLens = R.lens( | |
| (x) => x, | |
| (x) => x | |
| ); | |
| const handler = { | |
| get: function(target, name, reciever){ | |
| const nameAsInt = parseInt(name) | |
| if(!isNaN(nameAsInt)){ | |
| return createLensObject(R.compose(target, R.lensIndex(nameAsInt))) | |
| }else{ | |
| return createLensObject(R.compose(target, R.lensProp(name))) | |
| } | |
| } | |
| } | |
| function createLensObject(lens = blankLens){ | |
| return new Proxy(lens, handler) | |
| } | |
| const L = createLensObject(blankLens) | |
| // Access properties and indices on L to create a lens | |
| // L.x = R.lensProp("x") | |
| // L[0] = R.lensIndex(0) | |
| view(L.x, {x: 7}) // = 7 | |
| over(L[0].q, x => x + 3, [{q: 4}]) // [{"q": 7}] | |
| set(L.z.q, 5, {z: {q: 3}}) // {"z": {"q": 5}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment