Skip to content

Instantly share code, notes, and snippets.

@zipcode
Created February 6, 2014 19:59
Show Gist options
  • Save zipcode/8851497 to your computer and use it in GitHub Desktop.
Save zipcode/8851497 to your computer and use it in GitHub Desktop.
A quick and dirty jQuery implementation of Lenses. If you're into that sort of thing.
(function ($) {
$.lens = {};
$.lens.of = function (get, set) {
var lens = function (d) { return get(d); }
lens.set = set;
lens.modify = function (d, f) { return set(d, f(get(d))); }
lens.compose = function (other_lens) {
return $.lens.of(
function (d) { return other_lens(get(d)); },
function (d, v) { return set(d, other_lens.set(get(d), v)); }
)
}
return lens;
}
$.lens.array = function (n) {
return $.lens.of(
function (a) { return a[n] },
function (a, v) {
var a = a.slice(0);
a[n] = v;
return a;
}
)
}
$.lens.obj = function (n) {
return $.lens.of(
function (o) { return o[n] },
function (o, v) {
var o = $.extend({}, o);
o[n] = v;
return o;
}
)
}
Array.lens = $.lens.array;
Object.lens = $.lens.obj;
})(jQuery);
/*
var data = {
'marvel' : ['hulk'],
'dc' : ['super', 'man']
}
var lens = $.lens.obj('dc').compose($.lens.array(1))
var data2 = lens.set(data, "hero")
lens(data) // "man"
lens(data2) // "hero"
var data3 = lens.modify(data, function (s) { return s + "!!" })
$.lens.obj('dc')(data3) // ['super', 'man!!']
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment