JavaScript Function Overloading


SUBMITTED BY: Guest

DATE: June 12, 2013, 1:15 a.m.

FORMAT: JavaScript

SIZE: 2.2 kB

HITS: 878

  1. var def = function(functions, parent) {
  2. return function() {
  3. var types = [];
  4. var args = [];
  5. eachArg(arguments, function(i, elem) {
  6. args.push(elem);
  7. types.push(whatis(elem));
  8. });
  9. if(functions.hasOwnProperty(types.join())) {
  10. return functions[types.join()].apply(parent, args);
  11. } else {
  12. if (typeof functions === 'function')
  13. return functions.apply(parent, args);
  14. if (functions.hasOwnProperty('default'))
  15. return functions['default'].apply(parent, args);
  16. }
  17. };
  18. };
  19. var eachArg = function(args, fn) {
  20. var i = 0;
  21. while (args.hasOwnProperty(i)) {
  22. if(fn !== undefined)
  23. fn(i, args[i]);
  24. i++;
  25. }
  26. return i-1;
  27. };
  28. var whatis = function(val) {
  29. if(val === undefined)
  30. return 'undefined';
  31. if(val === null)
  32. return 'null';
  33. var type = typeof val;
  34. if(type === 'object') {
  35. if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
  36. return 'array';
  37. if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
  38. return 'date';
  39. if(val.hasOwnProperty('toExponential'))
  40. type = 'number';
  41. if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
  42. return 'string';
  43. }
  44. if(type === 'number') {
  45. if(val.toString().indexOf('.') > 0)
  46. return 'float';
  47. else
  48. return 'int';
  49. }
  50. return type;
  51. };
  52. var out = def({
  53. 'int': function(a) {
  54. alert('Here is int '+a);
  55. },
  56. 'float': function(a) {
  57. alert('Here is float '+a);
  58. },
  59. 'string': function(a) {
  60. alert('Here is string '+a);
  61. },
  62. 'int,string': function(a, b) {
  63. alert('Here is an int '+a+' and a string '+b);
  64. },
  65. 'default': function(obj) {
  66. alert('Here is some other value '+ obj);
  67. }
  68. });
  69. out('ten');
  70. out(1);
  71. out(2, 'robot');
  72. out(2.5);
  73. out(true);

comments powered by Disqus