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;
}

All Levels of Data Hiding in JavaScript

In the last post we talked about inheritance in pure JavaScript. Now we want to see how to implement data hiding (private, public, ...) in a JavaScript class.

 
var MyObj = (function() { // This is like a namespace
    var privateSharedVar = 'private shared value - (Java: private static)';

    function privateSharedFunction() {
        alert('Private shared function - (Java: private static)');
    }

    function MyObj() { // This is a public constructor
        var privateInstanceVar = 'Private instance value - Java: private';
        this.publicInstanceVar = 'Public instance value - Java: public';

        function privateInstanceFunction() {
           alert('Private instance function - (Java: private method)');
        };

        this.publicInstanceMethod = function() {
            alert('Public instance function - (Java: public method)');
        };
    }

    MyObj.prototype.publicSharedVar = 'Public shared value - (Java: public static)';

    MyObj.prototype.publicSharedMethod = function() {
        alert('Public shared function - (Java: Public static method)')
    };

    return MyObj;
})();

In this code we have all these levels:
  • Private fields
  • Public fields
  • Private methods
  • Public methods
  • Private static fields
  • Public static fields
  • Private static methods
  • Public static methods

Basic Inheritance in Pure JavaScript

JavaScript is a powerful Prototype Based Object Oriented scripting language.

This starting sentence is stating many facts about this language such as:

  1. Of course it is powerful ...
  2. Object Oriented languages are either Class Based (like C++, Java, ...) Or Prototype Based (like JavaScript, ActionScript, ...)
  3. It is a Scripting language which means it is interpreted not compiled (programming languages are compiled)

So, we are trying to show how to implement inheritance in a pure Prototype Based fashion, and we do not go for those framework specific solutions which are trying to bring Class Based fashion to JavaScript!

Scenario:
There is no better example than human beings for Object Orientation.

Father Class: Human
Child Class: Teacher

Anything could be a function in JavaScript so our Human class (Human function) would be like this:

function Human(name){ 
  this.name=name;  
}
 
Human.prototype.introduce=function(){ 
  alert("I am " + this.name)
}

// usage would be like this:

var john = new Human("John Smith");
john.introduce();


Now we write the Teacher class (Teacher function) which is extending Human.

// Here's where the inheritance occurs 
Teacher.prototype = new Human();        

// Otherwise instances of Teacher would have a constructor of Human 
Teacher.prototype.constructor = Teacher;       

function Teacher(name, field) { 
  this.name = name;
  this.field = field;
} 

Teacher.prototype.professionalIntroduce = function(){ 
  alert("My name is " + this.name + " and I am a " 
  + this.field + " teacher.");
} 

// usage
var marry = new Teacher("Marry Brown", "Chemistry");
marry.introduce();
marry.professionalIntroduce();


Download

Welcome

We will focus on the aspects of practical coding. You will start learning those things which are more needed in real world jobs. We publish videos and other materials for almost all languages.

Good luck