Last active
December 21, 2015 23:09
-
-
Save ericmoritz/6380142 to your computer and use it in GitHub Desktop.
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 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