Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ImaginaryDevelopment/6370194 to your computer and use it in GitHub Desktop.
Save ImaginaryDevelopment/6370194 to your computer and use it in GitHub Desktop.
maybe_without_objects adjusted for prototype calls and what not, in action at http://jsfiddle.net/Maslow/w8Uzw/
function type(obj) {
var obj_type = typeof obj;
return ({
is: function (type) {
return obj_type === type;
},
is_object: function () {
return obj_type === "object";
},
is_func: function () {
return obj_type === "function";
},
is_string: function () {
return obj_type === "string";
}
});
};
function maybe(item) {
return ({
result: function (accessor, __default) {
if (!item) return type(accessor).is_func() ? __default : accessor;
else return type(accessor).is_func() ? accessor(item) : item;
},
_: function (accessor) {
if (!item) return maybe(null);
if (!accessor && type(item).is_func()) {
return maybe(item());
}
if (type(accessor).is_string()) {
if (item.hasOwnProperty(accessor)) return maybe(item[accessor]);
var result = item[accessor];
if (result) return maybe(item[accessor].call(item));
return maybe(result);
}
if (type(accessor).is_func()) {
return maybe(accessor(item));
}
return maybe(item[accessor]);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment