diff options
author | matthewsotoudeh <matthewsot@outlook.com> | 2015-05-10 18:34:44 -0700 |
---|---|---|
committer | matthewsotoudeh <matthewsot@outlook.com> | 2015-05-10 18:34:44 -0700 |
commit | 5b04698aebf68c471db2146340b2a03f5b4549a3 (patch) | |
tree | a745735db1332cd02c8687e033045dd13fc09194 | |
parent | b5a7c325aa6102fc649420bebbafa2c49dc56dcb (diff) |
support for default arg values
-rw-r--r-- | README.md | 12 | ||||
-rw-r--r-- | jfn.js | 41 |
2 files changed, 44 insertions, 9 deletions
@@ -19,4 +19,16 @@ jfn.defineFunction("testFunction", "*", function (data) { testFunction("Hello!"); //String: Hello! testFunction(1); //Num: 1 testFunction({ "property": "value" }); //Catchall: {"property":"value"} +``` + +Default values are also possible: + +``` +// Returns the root of a number, defaulting to the square root +jfn.defineFunction(Math, "root", ["number", "number"], [2], function (base, power) { + return Math.pow(base, (1 / power)); +}); + +alert(Math.root(8, 3)); //2 (cubed root of 8) +alert(Math.root(9)); //3 (square root of 9) ```
\ No newline at end of file @@ -4,38 +4,60 @@ jfn.getProxyFunction = function (name) { return function () { var jfns = this[name]["__jfn"]["fns"]; + arguments = Array.slice(arguments); + for (var i = 0; i < jfns.length; i++) { var jfn = jfns[i]; - var matches = arguments.length === jfn.args.length; - for (var a = 0; a < jfn.args.length; a++) { - matches = jfn.args[a] === (typeof arguments[a]); + var matches = arguments.length <= jfn.args.length; + for (var a = 0; a < arguments.length; a++) { + matches = jfn.args[a] === "*" || jfn.args[a] === (typeof arguments[a]); if (!matches) { break; } } if (matches) { - jfn.fn.apply(this, arguments); - return; + var argIndex = jfn.args.length; + for (var d = (jfn.defaults.length - 1); d >= 0; d--) { + argIndex = argIndex - 1; + + if (typeof arguments[argIndex] === "undefined") { + arguments[argIndex] = jfn.defaults[d]; + } + } + + return jfn.fn.apply(this, arguments); } } //No match found! - if (this[name]["jfn"].hasOwnProperty("default")) { - this[name]["jfn"]["default"].apply(this, arguments); + if (this[name]["__jfn"].hasOwnProperty("default")) { + return this[name]["__jfn"]["default"].apply(this, arguments); } }; }; -jfn.defineFunction = function (object, name, args, fn) { +jfn.defineFunction = function (object, name, args, defaults, fn) { if (typeof object === "string") { - fn = args; + fn = defaults; + defaults = args; args = name; name = object; object = window; } + if (typeof args === "function") { + fn = args; + defaults = []; + args = []; + } + + if (typeof defaults === "function") { + fn = defaults; + defaults = []; + } + if (!object.hasOwnProperty(name)) { object[name] = jfn.getProxyFunction(name); } @@ -59,6 +81,7 @@ jfn.defineFunction = function (object, name, args, fn) { object[name]["__jfn"]["fns"].push({ args: args, + defaults: defaults, fn: fn }); };
\ No newline at end of file |