Skip to content

Instantly share code, notes, and snippets.

@andyhd
Created February 11, 2012 01:48
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save andyhd/1795108 to your computer and use it in GitHub Desktop.
Save andyhd/1795108 to your computer and use it in GitHub Desktop.
Javascript Lenses
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]
@slorber
Copy link

slorber commented Jan 22, 2014

nice!

did you see this library?
http://bilby.brianmckenna.org/#lenses

@acthp
Copy link

acthp commented Jan 16, 2015

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