Created
February 11, 2012 01:48
-
-
Save andyhd/1795108 to your computer and use it in GitHub Desktop.
Javascript Lenses
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
function lens(get, set) { | |
var f = function (a) { return get(a); }; | |
f.set = set; | |
f.mod = function (f, a) { return set(a, f(get(a))); }; | |
return f; | |
} | |
var first = lens( | |
function (a) { return a[0]; }, | |
function (a, b) { return [b].concat(a.slice(1)); } | |
); | |
console.log(first([1, 2, 3])); // outputs 1 | |
console.log(first.set([1, 2, 3], 5)); // outputs [5, 2, 3] | |
function tenTimes(x) { return x * 10 } | |
console.log(first.mod(tenTimes, [1, 2, 3])); // outputs [10, 2, 3] |
This is nice.
A bit odd that get & set take the data structure first, but mod takes it last. Looking at a couple lens libs, they always put the data structure last.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice!
did you see this library?
http://bilby.brianmckenna.org/#lenses