Created
December 23, 2014 23:14
-
-
Save ThomasCrevoisier/afc6f6f402f8e31f0deb to your computer and use it in GitHub Desktop.
A simple example using Maybe monad of MonetJS
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
| // Run the code with NodeJS | |
| var Monet = require('monet'); | |
| function getValue (obj, keysString) { | |
| var keys = keysString.split('.'); | |
| var curr = obj; | |
| keys.forEach(function (key) { | |
| if (curr) { | |
| curr = curr[key]; | |
| } | |
| }); | |
| return Monet.Maybe.fromNull(curr); | |
| } | |
| function print (value) { | |
| console.log(value); | |
| return value; | |
| } | |
| var add = function (a, b) { | |
| return a + b; | |
| }.curry(); | |
| var test = { | |
| yo: { | |
| first: 2, | |
| value: { | |
| second: 4 | |
| } | |
| } | |
| }; | |
| // Play with the second parameter of getValue and see what happens when you try non-existing keys | |
| var first = getValue(test, 'yo.first'); | |
| var second = getValue(test, 'yo.value.second'); | |
| var result = first.ap(second.map(add)); | |
| if (result.isSome()) { | |
| result.map(print); | |
| } else { | |
| console.log('None'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment