Last active
December 14, 2015 09:38
-
-
Save avovsya/5065808 to your computer and use it in GitHub Desktop.
Another one impletementation of "maybe" monad in JavaScript
This file contains 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
var o = { data: { success: true } } | |
maybe('o') | |
.with('data') | |
.with('success') | |
.if(function(x){ | |
return x === true; | |
}) | |
.do(function(x){ | |
if(x === null){return "if failed"} else{ return "if succeded"} | |
}) | |
.val() | |
maybe('o') | |
.with('no') | |
.with('data') | |
.val() |
This file contains 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
var maybe = (function(){ | |
function maybe(o){ | |
if(typeof this[o] !== "undefined" && this[o] !== null){ | |
return result(this[o]); | |
} else { | |
return result(null); | |
} | |
}; | |
function withFunc(obj, prop){ | |
if(obj && typeof obj[prop] !== "undefined" && obj[prop] !== null){ | |
return result(obj[prop]); | |
} else { | |
return result(null); | |
} | |
} | |
function result(obj){ | |
return { | |
with: function(prop){ | |
return withFunc(obj,prop); | |
}, | |
val: function(defaultValue){ | |
if(typeof obj !== "undefined" || obj !== null) { | |
return obj; | |
} | |
if(typeof defaultValue !== "undefined") return defaultValue; | |
return null; | |
}, | |
if: function(condition){ | |
if(condition(obj)){ | |
return result(obj); | |
} | |
return result(null); | |
}, | |
do: function(action){ | |
if(typeof obj !== "undefined" || obj !== null) { | |
return result(action(obj)); | |
} | |
return result(null); | |
} | |
} | |
} | |
return maybe | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment