Forked from timcharper/maybe_without_objects.js
Last active
December 21, 2015 21:39
-
-
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/
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
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