Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jonas Raoni Soares Silva http://jsfromhell.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Function Overloader //JavaScript Class


This class allows javascript functions to be overloaded.

[UPDATED CODE AND HELP CAN BE FOUND HERE]




Usage:

   1  
   2  myFunction = new Overloader;
   3  
   4  myFunction.overload(function(x){
   5  	document.write("Receives: NUMBER<br />");
   6  }, Number);
   7  
   8  myFunction.overload(function(x){
   9  	document.write("Receives: STRING<br />");
  10  }, String);
  11  
  12  myFunction.overload(function(x,y){
  13  	document.write("Receives: FUNCTION, NUMBER<br />");
  14  }, Function, Number);
  15  
  16  myFunction.overload(function(x,y){
  17  	document.write("Receives: NUMBER, STRING<br />");
  18  }, Number, String);
  19  
  20  //test...
  21  myFunction(function(){}, 123); //function + number version
  22  myFunction(123); //number version
  23  myFunction("ABC"); //string version
  24  myFunction(123, "ABC"); //number + string version
  25  myFunction({}); /*There's no Object version, so the function will choose the one that has more arguments in common and if there isnt a "best match", it will use the first function that was overloaded...*/



Here's the code

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com/classes/overloader [v1.0]
   4  
   5  Overloader = function(){ //v1.0
   6  	var f = function(args){
   7  		var i, h = "#";
   8  		for(i in args = [].slice.call(arguments))
   9  			h += args[i].constructor;
  10  		if(!(h = f._methods[h])){
  11  			var x, j, k, m = -1;
  12  			for(i in f._methods){
  13  				for(j in args.length > (k = 0, x = f._methods[i][1]).length ? x : args)
  14  					(args[j] instanceof x[j] || args[j].constructor == x[j]) && ++k;
  15  				k > m && (h = f._methods[i], m = k);
  16  			}
  17  		}
  18  		return h ? h[0].apply(f, args) : undefined;
  19  	};
  20  	f._methods = {};
  21  	f.overload = function(f, args){
  22  		this._methods["#" + (args = [].slice.call(arguments, 1)).join("")] = [f, args];
  23  	};
  24  	f.unoverload = function(args){
  25  		return delete this._methods["#" + [].slice.call(arguments).join("")];
  26  	};
  27  	return f;
  28  };
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS