Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save hiroshi-maybe/f2feb320d39196cc7c16 to your computer and use it in GitHub Desktop.

Select an option

Save hiroshi-maybe/f2feb320d39196cc7c16 to your computer and use it in GitHub Desktop.
Casual argument parser in JavaScript
"use strict";
/****** Library START ******/
var hike = function() {
var user_fn, i, len, rule_strs, rule_parsed,
rule = {}, /* arg length -> [arg name] */
_arguments = Array.prototype.slice.call(arguments);
user_fn = _arguments.pop();
if (toString.call(user_fn) !== '[object Function]') {
throw "Need user function in the last argument";
}
rule_strs = _arguments;
len = rule_strs.length;
// Parse rules in inverted order to prioritize former rules
for (i=len-1; i>=0; i-=1) {
rule_parsed = _hike_parse(rule_strs[i]);
rule[rule_parsed.length] = rule_parsed;
}
return function() {
var this_rule, i, args = {},
args_len = arguments.length;
this_rule = rule[args_len];
if (this_rule === void 0) {
throw "Cannot match argument rule. Args length: "+args_len;
}
for (i=0; i<args_len; i+=1) {
args[this_rule[i]] = arguments[i];
}
user_fn(args);
};
};
var _hike_parse = function(rule_str) {
var i, len, args, rule = [];
args = rule_str.split(',');
len = args.length;
for (i=0; i<len; i+=1) {
// TODO: Support annotation (e.g. type, required, ..)
rule.push(args[i].trim());
}
return rule;
};
/****** Library END ******/
var fade = hike("duration, complete",
"options",
"duration, easing, complete",
function(args){
console.log(args);
});
// http://api.jquery.com/fadeIn/
fade(100,function() { console.log("Faded"); });
fade({
"duration" : 100,
"easing" : "swing",
"completed": function() { console.log("Faded"); }
});
fade(100,"swing",function() { console.log("Faded"); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment