pathterminuspages/snippets/aboutcontactabout me

Function overload in javascript

04-12-2017

Overload is to allow several functions with same name, nut different type-signature. This is somewhat unecessary working with java script since java script is one of the weakest typed languages out there. But who cares. You can't overload a function in JS, but with some lambda magic:

//printing to p-elm with id output var print = (function(){ var outP = document.getElementById("output"); return function(str){ outP.innerHTML += str + "<br>"; }; })(); var overload = function(fInt,fStr,fBool,fFunc){ return function(arg1){ switch(typeof arg1){ case "number": return fInt(arg1); case "string": return fStr(arg1); case "boolean": return fBool(arg1); case "function": return fFunc(arg1); } }; }; //Commence overloading var func0 = overload( function(intArg){ print("Hi, i'm a number' : " + intArg); }, function(strArg){ print("Hi, i'm a string : " + strArg); }, function(boolArg){ print("I'm boolean, and that is " + boolArg); }, function(funcArg){ print(funcArg("Hi, i'm a function, and I return!")); } ); func0("Yes, I am!"); func0(42); func0(100); func0(true); func0(retstr => retstr); //result: // Hi, i'm a string : Yes, I am! // Hi, i'm a number' : 42 // Hi, i'm a number' : 100 // I'm boolean, and that is true // Hi, i'm a function, and I return!

Now, we can even do it more dynamically by adding a more advanced overloader:

var overload = function(fs){ var argParser = function(args){ var argsTacc = ""; for(var i = 0; i < args.length; i++){ argsTacc += typeof args[i]; if(i !== args.length - 1){ argsTacc += ","; } } return argsTacc; }; return function(args){ var pArgs = argParser(args); if(fs[pArgs] !== undefined){ return fs[pArgs](args); } return function(args){ return null; }; }; };

And we get:

var func1 = overload({ "string,number":function(args){ print("overload string,number"); print("stringArg : " + args[0]); print("numberArg : " + args[1]); print("*"); }, "string":function(args){ print("overload string"); print("stringArg : " + args[0]); }, "string,string":function(args){ print("overload string,string"); print("stringArg1 : " + args[0]); print("stringArg2 : " + args[1]); print("*"); }, "function":function(args){ print("overload function"); print("functionArg1 : " + args[0]("From in here!")); print("*"); } }); func1(["I'm a string. Below is my number",42]) func1(["I'm a string, but im only one."]); func1(["I'm string number one.","I'm not a number!"]); func1([out => "I'm a function, and i'm saying hello. " + out]);

With output:

overload string,number
stringArg : I'm a string. Below is my number
numberArg : 42
*
overload string
stringArg : I'm a string, but im only one.
overload string,string
stringArg1 : I'm string number one.
stringArg2 : I'm not a number!
*
overload function
functionArg1 : I'm a function, and i'm saying hello. From in here!
*

CommentsGuest Name:Comment: