Skip to content

Instantly share code, notes, and snippets.

@ericmoritz
Last active December 21, 2015 23:09
Show Gist options
  • Select an option

  • Save ericmoritz/6380142 to your computer and use it in GitHub Desktop.

Select an option

Save ericmoritz/6380142 to your computer and use it in GitHub Desktop.
function maybe(x) {
return {
bind: function(f) {
if(x == null) {
return null;
} else {
return f(x);
}
},
getDefault: function(y) {
return y ? x == null : x
}
}
}
function lookup(key, obj) {
return function(obj) {
return maybe(obj[key]);
};
};
function getNested(obj) {
var keys = [].slice.call(arguments, 1);
return [].reduce.call(keys,
function(m, key) {
return m.bind(lookup(key));
},
maybe(obj)
);
}
obj = {"foo": {"bar": "baz"}};
console.log(
maybe(obj.foo).bind(lookup("bar")).getDefault(null)
);
console.log(
maybe(obj.foo).bind(lookup("bing")).getDefault(null)
);
console.log(getNested(obj, "foo", "bar").getDefault(null));
console.log(getNested(obj, "foo", "bing").getDefault(null));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment