Skip to content

Instantly share code, notes, and snippets.

@avovsya
Last active December 14, 2015 09:38
Show Gist options
  • Save avovsya/5065808 to your computer and use it in GitHub Desktop.
Save avovsya/5065808 to your computer and use it in GitHub Desktop.
Another one impletementation of "maybe" monad in JavaScript
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()
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