Skip to content

Instantly share code, notes, and snippets.

@ysksn
Created May 6, 2016 00:00
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 ysksn/d973ce0d86295c2a10984cd9a77276fe to your computer and use it in GitHub Desktop.
Save ysksn/d973ce0d86295c2a10984cd9a77276fe to your computer and use it in GitHub Desktop.
/*global _ */
/*jslint
browser : true, continue : true,
devel : true, indent : 2, maxerr : 50,
newcap : true, nomen : true, plusplus : true,
regexp : true, sloppy : true, vars :false,
white : true
*/
var _ = require('underscore');
var my_functions = {
fail: function(thing) { throw new Error(thing); },
existy: function(x) { return x != null; },
truthy: function(x) { return (x !== false) && my_functions.existy(x); },
doWhen: function(cond, fun) {
if(my_functions.truthy(cond)) { return fun(); }
return undefined;
},
invoker: function(name, method) {
return function(target /* */) {
if(!my_functions.existy(target)) { my_functions.fail('Must provide a target'); }
var
args = _.rest(arguments),
targetMethod = target[name];
return my_functions.doWhen((my_functions.existy(targetMethod) && method === targetMethod), function() {
return targetMethod.apply(target, args);
});
};
},
makeUniqueStringFunction: function(start) {
var counter = start;
return function(prefix) {
return [prefix, counter++].join('');
};
},
checker: function(/* */) {
var validators = _.toArray(arguments);
return function(obj) {
return _.reduce(validators, function(errs, check) {
if(check(obj)) { return errs; }
return _.chain(errs).push(check.message).value();
}, []);
};
},
validator: function(message, fun) {
var f = function(/* */) {
return fun.apply(fun, arguments);
};
f.message = message;
return f;
}
};
module.exports = my_functions;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment