Overloaded function in Javascript


Coming from Java background, it is happened to be searched java language constructs while coding javascript. One of such construct is overloaded methods/function. Take a look following code snippet
 
//Normal sum
var intergerSum = sum(10, 20);
//Expecting item price sum
var objectSum = sum(
  {item_id:'01',name:'abc', price:100},
  {item_id:'02',name:'xyz', price:200}
);

As per above code snippet, implementation of ‘sum’ has been abstracted from the user. In the world of type safe language like Java, it is very straight forward, but in case of javascript we need to have our custom implementation. Lets see how can we achieve above in javascript.
Lets start with defining a constructor function which introduce a common function to all our custom object so that we can extract integer value for summation.

//constructor function to introduce new function to custom object
function item(options) {
  var instance = Object.create(item.prototype);
  for(property in options) {
      instance[property] = options[property];
      instance[property] = options[property];
  }
  return instance;
}

item.prototype = {
  valueOf : function() {
    console.log('Inside prototype');
    return this.price;
  },
  type: 'item'
};

As per above code snippet, item() construction function return new object with special function valueOf(). Lets execute our initial code snippet with little modification

//Normal sum
var integerSum = sum(10, 20);
//Expecting item price sum
var objectSum = sum(
  item({item_id:'01',name:'abc', price:100}),
  item({item_id:'02',name:'xyz', price:200})
);
console.log(integerSum);//=> 30
console.log(objectSum);//=> 300

So we have overloaded sum() which seamlessly return summation for literal to custom object.

Comments

Popular posts from this blog

State Design Pattern by Example

Eclipse command framework core expression: Property tester

Composite Design Pattern by example