Skip to content

Instantly share code, notes, and snippets.

@phlik
Last active January 2, 2016 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phlik/8250791 to your computer and use it in GitHub Desktop.
Save phlik/8250791 to your computer and use it in GitHub Desktop.
One of my many attempts to create behavior like a maybe monad in javascript.
var maybe = function(item) {
var __internal = item;
this.result = function(accessor, __default) {
if (!__internal) {
return new type(accessor).is_func() ? __default : accessor;
}
return new type(accessor).is_func() ? accessor(__internal) : __internal;
};
this.select = function(accessor) {
if (!__internal) {
return new maybe(null);
}
if (new type(accessor).is_string()) {
return new maybe(__internal[accessor]);
}
else {
return new maybe(accessor(__internal));
}
};
function type(obj) {
this.is = function(type) {
return typeof obj === type;
};
this.is_object = function() {
return typeof obj === "object";
};
this.is_func = function() {
return typeof obj === "function";
};
this.is_string = function() {
return typeof obj === "string";
};
}
};
/*Testing Starts Here*/
var test = {
address: {
city: null,
homes: ["first", "second"]
}
};
var mec = new maybe(test).select(function(c) {
return c.address;
}).select(function(c) {
return c.city;
}).result(function(c) {
return c;
}, "__default");
console.log(mec);
var meh = new maybe(test).select("address").select("homes").result({
default:
"yarrs"
});
console.log(meh[0]);
var test = {
address: {
city: 'crazy'
}
};
var maybe = function (item) {
var maybeProto = {
__internal : item,
result : function (accessor, __default) {
if (!__internal) {
return typeof accessor === "string" ? accessor : __default;
}
if (typeof accessor === "string"){
return __internal;
}
else { return accessor(__internal); }
},
select : function (accessor) {
if (!__internal) { return new maybe(null); }
if (typeof accessor === "string"){
return new maybe(__internal[accessor]);
}
else { return new maybe(accessor(__internal)); }
}
};
return maybeProto;
};
var mec = new maybe(test)
.select(function (c) { return c.address; })
.select(function (c) { return c.city; })
.result(function (c) { return c; }, "__default");
alert(mec);
var meh = new maybe(test)
.select("address")
.select("city")
.result("__default");
alert(meh);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment