Skip to content

Instantly share code, notes, and snippets.

@kmdsbng
Created March 29, 2012 02:49
Show Gist options
  • Select an option

  • Save kmdsbng/2232730 to your computer and use it in GitHub Desktop.

Select an option

Save kmdsbng/2232730 to your computer and use it in GitHub Desktop.
Maybe monad? in JavaScript
// usage:
// var target = {hoge: {fuga: 'muga'}};
// maybe(target, 'hoge', 'fuga') //=> 'muga'
// maybe(target, 'moge', 'fuga') //=> undefined
// maybe(target, 'hoge', 'fuga', ['match', /^m/]) //=> ['m']
// maybe(target, 'moge', 'fuga', ['match', /^m/]) //=> undefined
function maybe() {
var self = arguments[0];
var methodChain = [].slice.apply(arguments, [1]);
var len = methodChain.length;
for (var i=0; i < len; ++i) {
var ops = methodChain[i];
if (typeof(ops) === 'string')
ops = [ops];
var message = ops[0];
var args = ops.slice(1);
if (self === undefined || self === null) {
self = undefined;
} else {
if (typeof(self[message]) === 'function') {
self = self[message].apply(self, args);
} else {
self = self[message];
}
}
}
return self;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment