Skip to content

Instantly share code, notes, and snippets.

@poying
Created January 14, 2014 04:27
Show Gist options
  • Save poying/8413028 to your computer and use it in GitHub Desktop.
Save poying/8413028 to your computer and use it in GitHub Desktop.
'use strict';
var utils = module.exports = {};
utils.args = function (defval, names) {
defval || (defval = {});
names || (names = []);
var map = {};
names.forEach(function (val) {
map[val.length] = val;
});
return function (args) {
var newargs = Object.create(defval);
var names = map[args.length];
if (!names) {
throw new Error('Wrong arguments');
}
names.forEach(function (name, index) {
newargs[name] = args[index];
});
return newargs;
};
};
utils.function = function (defval, names, fn) {
var getArgs = utils.args(defval, names);
return function () {
return fn.call(this, getArgs(arguments));
};
};
@poying
Copy link
Author

poying commented Jan 14, 2014

var fn = utils.function({hello: 'world', ghostisland: 'taiwan'}, [['hello', 'ghostisland'], ['ghostisland']], function (args) {
  console.log(args);
});

fn('taiwan', 'lol');
fn('lol');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment