Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Chained Calculator in JavaScript

This is a very small yet complete example of a chain design pattern implementation in JavaScript. Please feel free to ask questions if the comments are not that descriptive.
var Calc = function (value) {
  /* for more security */
  var me = this; 

  /* chaning function to add  */
  this.add = function(x) {
    value += x;
    return me;
  }
  
  /* chaining function to multiply */
  this.multiply = function(x) {
    value *= x;
    return me;
  }
  
  /* chaining function to subtract */
  this.subtract = function(x) {
    value -= x;
    return me;
  }

  /* chaning function to divide  */
  this.divide = function(x) {
    value /= x;
    return me;
  }
  
  /* chaining function to give the result */
  this.equals = function(callback) {
    callback(value);
    return me;
  }

  /* nomal function to return the result
     and to finish the chanin.
  */
  this.end = function() {
    return value;
  }
}


/*

How to use the calculator

*/

var calc = new Calc(10)
  .add(20)
  .multiply(4)
  .equals(function (result) {
    console.log("= " + result);
  })
  .add(1).equals(function(result) {
    console.log(result);
  }).divide(3);


console.log("final result: " + calc.end());

How to Use Function Arguments Wisely in JavaScript

In JavaScript function arguments are untyped and are not mandatory to be provided when we call the function.

function sum(a, b, c) {
  return a + b + c;
}

So we can call function sum like these:

console.log(sum(10));
console.log(sum(20, 10));
console.log(sum(20, 10, 30));
console.log(sum(20, 10, 30, 5));

Surprisingly all of these are valid and never lead in a runtime error!
And on the 4th call, 5 will be ignored by our code.

Those arguments who which are not provided will be assigned by 'undefined'. So we can check any argument in the body of the function to see if it is provided or not like this:

function sum2(a, b, c) {
  if (a != undefined && b != undefined && c != undefined) {
    return a + b + c;
  } else {
    return 0;
  }
}

In the function of sum2 we expect the user to provide all 3 arguments, otherwise we return 0.
There is a special object called arguments available to all JavaScript functions which is working like an array containing all passed arguments.

So we can rewrite our function like this in order to work with any number of arguments:

function sum() {
  var result = 0;

  for (var i = 0; i < arguments.length; ++i) {
    result += arguments[i];
  }

  return result;
}