summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormatthewsotoudeh <matthewsot@outlook.com>2015-05-10 17:40:27 -0700
committermatthewsotoudeh <matthewsot@outlook.com>2015-05-10 17:40:27 -0700
commit393e4f220fafcaade28d31f49d16381099d6591a (patch)
treee22b005e411bf2febc626c7fe43121a2d269098d
parent53fbda210ef4404d3049d0fcd2b8261d1a61f585 (diff)
basic overloadable functions
-rw-r--r--README.md15
-rw-r--r--jfn.js54
2 files changed, 69 insertions, 0 deletions
diff --git a/README.md b/README.md
index e743971..c72c0ce 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,17 @@
# jfn
Playing around with Javascript functions
+
+A global overloadable function:
+
+```
+jfn.defineFunction("testFunction", ["string"], function (str) {
+ alert("String: " + str);
+});
+
+jfn.defineFunction("testFunction", ["number"], function (num) {
+ alert("Num: " + num);
+});
+
+testFunction("Hello!"); //String: Hello!
+testFunction(1); //Num: 1
+``` \ No newline at end of file
diff --git a/jfn.js b/jfn.js
new file mode 100644
index 0000000..90b725e
--- /dev/null
+++ b/jfn.js
@@ -0,0 +1,54 @@
+var jfn = {};
+
+jfn.getProxyFunction = function (name) {
+ return function () {
+ var jfns = this[name]["__jfns"];
+
+ 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]);
+ if (!matches) {
+ break;
+ }
+ }
+
+ if (matches) {
+ jfn.fn.apply(this, arguments);
+ return;
+ }
+ }
+ };
+};
+
+jfn.defineFunction = function (object, name, args, fn) {
+ if (typeof object === "string") {
+ fn = args;
+ args = name;
+ name = object;
+ object = window;
+ }
+
+ if (!object.hasOwnProperty(name)) {
+ object[name] = jfn.getProxyFunction(name);
+ }
+
+ if (!object[name].hasOwnProperty("__jfns")) {
+ object[name]["__jfns"] = [];
+ } else {
+ for (var i = 0; i < object[name]["__jfns"].length; i++) {
+ var f = object[name]["__jfns"][i];
+ if (JSON.stringify(f.args) === JSON.stringify(args)) {
+ object[name]["__jfns"].splice(i, 1);
+ return;
+ }
+ }
+ }
+
+ object[name]["__jfns"].push({
+ args: args,
+ fn: fn
+ });
+}; \ No newline at end of file
generated by cgit on debian on lair
contact matthew@masot.net with questions or feedback