Tuesday, September 13, 2016

JavaScript functional and prototype inheritance

In JavaScript there are 2 options for class  inheritance: functional(regular - well known by other OO languages) and prototype(own style based on "cloning").

1. Preparation 


First of all we need several files:- html file for displaying test results: test.html- our script file with algorythm implementation: MyScript.js- file with test scripts for previous step: MyScriptTest.js- libraries mocha.js and chai.js - they will be used as external scripts.All this files I put to one directory. Here is the content of test result file: test.html:



<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

  <!-- Mocha css -->  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.css">
  <!-- Mocha dependency -->  <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
  <!-- Mocha: setup BDD -->  <script> mocha.setup('bdd'); </script>
  <!-- chai dependency -->  <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
  <!-- export assert -->  <script>  var assert = chai.assert;  </script>
</head>

<body>
  <!-- script which should be tested -->  <script src="MyScript.js"></script>
  <!-- test itself -->  <script src="MyScriptTest.js"></script>
  <!-- element with id="mocha" for test results -->  <div id="mocha"></div>
  <!-- run tests! -->  <script>
    mocha.run();
  </script>
</body>
</html>

As you can see, mocha and chai libraries will be downloaded by SRIPT tag. Also we set up mocha for using BDD, exported "assert" for simple usage and executed mocha test running.
In addition, we need just 2 files:
<!-- script which should be tested --><script src="MyScript.js"></script>
<!-- test itself --><script src="MyScriptTest.js"></script>

- we will be creating them step-by-step during implementation. First - function for MyScript, next - testblock for that function in MyScriptTest.js.

2. Functional inheritance

Let's create a regular class:

function FuncPoint(x, y) {
    var _x = x, _y = y, self = this;

    self.getX = function () {
        return _x;
    };
    self.getY = function () {
        return _y;
    };
    self.toString = function () {
        return "[" + _x + "," + _y + "]";
    };
    return self;
}

- it has 2 private variables: _x and _y, we also created just "getters"(getX and getY) for this variables - so our class in "immutable": we can not change it after creation. Beside the we added "toString" method for printing our object in "user friendly" style.

Let's test it:
it("should be getX, getY, toString functions in FuncPoint class", function () {
    var p = new FuncPoint(1, 2);
    assert.equal(p.getX(), 1);
    assert.equal(p.getY(), 2);
    assert.equal(p.toString(), "[1,2]");
});


2.1 Child class in functional inheritance style. 

Now let's imagine, we have to extend our class for adding more(we want to add information about color to our point) functionality:

function FuncColoredPoint(x, y, color) {
    FuncPoint.call(this, x, y);
    var _color = color, self = this;

    self.getColor = function () {
        return _color;
    };

    var parentToString = self.toString;
    self.toString = function () {
        return parentToString() + "#" + _color;
    };

    return self;
}

Everything looks more or less similar to what we have in other OO languages:
- we can  to call "parent" constructor : FuncPoint.call(this, x, y);
so, no needs to create own variables _x and _y - the will be "inherited" from parent(FuncPoint) class.
- we can add additional properties(color) and methods(getColor)
- we can "override" methods by just defining the method with the same name:  self.toString = function () {....} and if we want to use "parent" function in "overriding" we can "copy" it to another variable(var parentToString = self.toString;) and use from it:  return parentToString() + "#" + _color;

Test:
it("should inherited getX and getY functions beside own function getColor and overriden function toString in FuncColoredPoint class", function () {
    var p = new FuncColoredPoint(2, 3, "RED");
    assert.equal(p.getX(), 2);
    assert.equal(p.getY(), 3);
    assert.equal(p.getColor(), "RED");
    assert.equal(p.toString(), "[2,3]#RED");
});

Everything is working, functional inheritance is clear and simple for understanding.

3. Prototype inheritance

Every JavaScript object has a prototype. The prototype is also an object.
All JavaScript objects inherit their properties and methods from their prototype. 
All JavaScript objects inherit the properties and methods from their prototype.
Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.

Concept of "class" is absent in JavaScript, there are just "objects" which are created by functions. So when we are creating object by new.... operator we are creating object by "prototype".

For example, we have regular function which creates object:
function ProtoPoint(x, y) {
    this.x = x;
    this.y = y;
}

When we creating object "p = new ProtoPoint" - we are creating object with property "__proto__" which is our case was inherited from Object.prototype property:
  1. ProtoPoint {x1y2}
    1. x:1
    2. y:2
    3. __proto__:Object

there are a lot of interesting things inside it:
  1. ProtoPoint {x1y2}
    1. x:1
    2. y:2
    3. __proto__:Object
      1. constructor:ProtoPoint(x, y)

      2. __proto__:Object
        1. __defineGetter__:__defineGetter__()
        2. __defineSetter__:__defineSetter__()
        3. __lookupGetter__:__lookupGetter__()
        4. __lookupSetter__:__lookupSetter__()
        5. constructor:Object()
        6. hasOwnProperty:hasOwnProperty()
        7. isPrototypeOf:isPrototypeOf()
        8. propertyIsEnumerable:propertyIsEnumerable()
        9. toLocaleString:toLocaleString()
        10. toString:toString()
        11. valueOf:valueOf()
        12. get __proto__:__proto__()
        13. set __proto__:__proto__()

For example we have a methods which were inherited from Object class like "hasOwnProperty" "toString" and others.

3.1 Adding methods to prototype.

"__proto__" is just a property, so we can add to it methods:
ProtoPoint.prototype.getX = function () {
    return this.x;
};

ProtoPoint.prototype.getY = function () {
    return this.y;
};

ProtoPoint.prototype.toString = function () {
    return "[" + this.x + "," + this.y + "]";
};

- it's just another option of defining object methods.

Test:
it("should getX, getY, toString functions added to PROTOTYPE", function () {
    var p = new ProtoPoint(4, 5);
    assert.equal(p.getX(), 4);
    assert.equal(p.getY(), 5);
    assert.equal(p.toString(), "[4,5]");
});

Everything is working just like methods were defined inside function "ProtoPoint". But where is one not very good thing here: our variables x and y are visible outside and we can't make them private:

it("should be visible outside local variable - we can't make them private :(", function () {
    var p = new ProtoPoint(6, 7);
    assert.equal(p.x, 6);
    assert.equal(p.y, 7);
});


3.2 Prototype inheritance. 

For prototype inheritance we can just create independent standalone class, and ones we decided to make it "inherited" from another - we can just change it __proto__ object:

function ProtoColoredPoint(x, y, color) {
    ProtoPoint.call(this, x, y);
    this.color = color;
}

ProtoColoredPoint.prototype = Object.create(ProtoPoint.prototype);

ProtoColoredPoint.prototype.getColor = function () {
    return this.color;
};

ProtoColoredPoint.prototype.toString = function () {
    return ProtoPoint.prototype.toString.call(this) + "#" + this.color;
};

For calling "parent" functions on overriding we can use ProtoPoint.prototype.PARENT_FUNCTION.call


Let's test it:
it("should be class ProtoColoredPoint with inherited methods form ProtoPoint", function () {
    var p = new ProtoColoredPoint(8, 9, "BLACK");
    assert.equal(p.getX(), 8);
    assert.equal(p.getY(), 9);
    assert.equal(p.getColor(), "BLACK");
    assert.equal(p.toString(), "[8,9]#BLACK");
});

4. The end.

Source code can be downloaded from here

Friday, September 9, 2016

JavaScript Functions: bindings, bindings, borrowing, decoratings


In JavaScript functions are object, so we can do a lot a things with them, which we can't do in many other languages.

1. Preparations.

First of all we need several files:
- html file for displaying test results: test.html
- our script file with algorythm implementation: MyScript.js
- file with test scripts for previous step: MyScriptTest.js
- libraries mocha.js and chai.js - they will be used as external scripts.
All this files I put to one directory. Here is the content of test result file: test.html:


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

  <!-- Mocha css -->  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.css">
  <!-- Mocha dependency -->  <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
  <!-- Mocha: setup BDD -->  <script> mocha.setup('bdd'); </script>
  <!-- chai dependency -->  <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
  <!-- export assert -->  <script>  var assert = chai.assert;  </script>
</head>

<body>
  <!-- script which should be tested -->  <script src="MyScript.js"></script>
  <!-- test itself -->  <script src="MyScriptTest.js"></script>
  <!-- element with id="mocha" for test results -->  <div id="mocha"></div>
  <!-- run tests! -->  <script>
    mocha.run();
  </script>
</body>
</html>

As you can see, mocha and chai libraries will be downloaded by SRIPT tag. Also we set up mocha for using BDD, exported "assert" for simple usage and executed mocha test running.
In addition, we need just 2 files:
<!-- script which should be tested --><script src="MyScript.js"></script>
<!-- test itself --><script src="MyScriptTest.js"></script>

- we will be creating them step-by-step during implementation. First - function for MyScript, next - testblock for that function in MyScriptTest.js.

2. Add new method(function) to function.

It can sound weird: add function to function. But in JavaScript, functions - are objects so, like add method to object, we can add new methods to function.

For example, we have a function:
function trace(message) {
    console.log(message);
}

- we can add additional function to it:
trace.description = function () {
    return "this function is printing messages to console";
}

After that, execution of "trace("hello")" - will print "hello" to console as designed. But also we can call "trace.description()" and  get it "description". 

Test: 
it("should be function description as a result when calling added method [trace.description()]", function () {
    assert.equal(trace.description(), "this function is printing messages to console");
});

3. Add new method to object:  "static" method to "object class".

The same thing(add function) we can do with objects:
function Point(x, y) {
    this.x = x;
    this.y = y;
}

We can add additional methods to Point functions, which our object constructor:
Point.equals = function (p1, p2) {
    return (p1.x == p2.x && p2.y == p2.y);
}

Point.clone = function (anotherPoint) {
    return new Point(anotherPoint.x, anotherPoint.y);
}

Tests:
it("should be working static function Point.equals(p1, p2) for POINT object comparison", function () {
    var p1 = new Point(1, 2);
    var p2 = new Point(1, 2);
    assert.equal(Point.equals(p1, p2), true);
});

it("should be working static function Point.clone(anotherPoint) for POINT cloning", function () {
    var p1 = new Point(1, 2);
    var p2 = Point.clone(p1);
    assert.equal(p2.x, 1);
    assert.equal(p2.y, 2);
});

4. Manipulations with "this"(context) variable.

In JavaScript, functions are objects. JavaScript functions have properties and methods. call() and apply() are predefined JavaScript function methods. Both methods can be used to invoke a function, and both methods must have the owner object as first parameter. Both methods take an owner object as the first argument. The only difference is that call() takes the function arguments separately, and apply() takes the function arguments in an array.

Let's see how can we use CALL function method:

Functions in JavaScript have no connection with context. So we can create function this way:
function pointToString(message) {
    return message + ":[" + this.x + "," + this.y + "]";
}

variable "this"  is absent but we can set it in explicit way using "call":
function pointToStringExec(point, message) {
    return pointToString.call(point, message);
}
- now pointToString will be executed with POINT as "this" variable.

Test:
describe("Explicit set of THIS(context) by executing CALL method", function () {
    it("should be formatted output of POINT with MESSAGE by executing pointToString.call(point,message)", function () {
        var p = new Point(1, 2);
        assert.equal(pointToStringExec(p, "point"), "point:[1,2]");
    });
});


5. Function borrowing.

Also, it's possible to "borrow" method from another object.
"Donor" object:

function Talker() {
    this.sayHi = function () {
        return "Hi!";
    }
}
var talker = new Talker();

"Borrower" object:
function LazyTalker() { }
var lazyTalker = new LazyTalker();
lazyTalker.greet = talker.sayHi;


Lazy talker is "borrowing" function "sayHi" from object Talker and using it as it own function "greet".

Test:
describe("Method borrowing", function () {
    it("Method LazyTalker.greet has to be BORROWED from Talker.sayHi", function () {
        assert.equal(lazyTalker.greet(), "Hi!");
    });
});

6.Context binding.

We use the Bind () method primarily to call a function with the this value set explicitly. It other words, bind () allows us to easily set which specific object will be bound to this when a function or method is invoked.
 
For every method we can call .bind method to set context on it execution.

Let's create an object:
function ExtendedPoint(x, y) {
    this.x = x;
    this.y = y;
    this.toString = function (message) {
        return message + ":[" + this.x + "," + this.y + "]";
    };
}

toString method is executing based on this.x and this.y values form object context. But we can bind it to another context(by binding it to another object):

function createPointToStringContextWrapper(p) {
    var point = new ExtendedPoint();
    return point.toString.bind(p);
}
- this function bind method Point.toString to context defined by parameter "p". How we can use it:

var zeroContextWrapper = createPointToStringContextWrapper(new ExtendedPoint(0, 0));
-now variable(in fact it's a function) zeroContextWrapper will be executing toString method as it is executing on object ExtendedPoint(0, 0)


Test:
it("should be zero message with binding of object [0,0] as a context", function () {
    assert.equal(zeroContextWrapper("zero"), "zero:[0,0]");
});

7. Partial functions.

Beside binding of function context, we can bind also function arguments.
function add(x, y) {
    return x + y;
}

var add1 = add.bind(null, 1);
var add2 = add.bind(null, 2);

- we are binding null as a context(because we don't need it) and 1 or 2 as first argument.

Test:
it("should be working functions add1 and add2 when we bind first parameter of add(x,y) function to 1 and 2", function () {
    assert.equal(add1(9), 10);
    assert.equal(add2(8), 10);
});

8. Decoration.

By calling .apply method we can execute function. So, we can decorate one function around another.

In next example we are using timerDecorator function which is decorating execution of any other function which is passed as "func" parameter by 2 time operations, for counting how much time function was running.

function timerDecorator(func, timerArr) {
    return function() {         
         var start = performance.now();         
         var result = func.apply(this, arguments); 
         var execTime = performance.now() - start; 
         timerArr.push(execTime); 
         return result; 
     }
}

var arr=[];
var addDecorated = timerDecorator(add, arr);

test:
describe("Decorated", function () {
    it("should be execution of decorated function with timing added to arrar ARR", function () {
        var result = addDecorated(1, 2);
        assert.equal(result, 3);
        assert.equal(arr.length, 1);
    });
});

9.The end.

Source code can be downloaded from here.

Wednesday, September 7, 2016

JavaScript closures - basic examples

Closures topic can be not obvious for developers which came from another languages like Java. So let's try to understand "why?".

1. What is "closure"? 


In shorts: JavaScript doesn't have PRIVATE access modifier. So closures it's the only way to limiting access.

From Wiki:
In programming languagesclosures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functionsOperationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b] A closure—unlike a plain function—allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.


Summary: function have access to variables defined on the upper levels:

var counter=0;
  function inc() {
     return++counter;
  }

Everything is pretty simple here. But what is we have the same inside another function? Like this:

function CreateCounter() {
  var counter=0;
  return function() {
     return++counter;
  }
}

Let's do this in developer console and after that define variable:
var inc=CreateCounter()

Value of this variable is:
>inc
function() {
     return++counter;
  }

So "inc" - is now function which "closed" around  scope of "parent" function. Scope of parent function has just one variable: "counter". And by every next invocation on inc()  this variable will be increased. We can create another counter by next call: var anotherInc=CreateCounter()
CreateCounter() function will create new variable   var counter=0 and return function which will be "closed" around it(linked) with it. So new counter will be independent of the previous one.

Let's try it in practice.

2. Preparations. 

First of all we need several files:
- html file for displaying test results: test.html
- our script file with algorythm implementation: MyScript.js
- file with test scripts for previous step: MyScriptTest.js
- libraries mocha.js and chai.js - they will be used as external scripts.
All this files I put to one directory. Here is the content of test result file: test.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

  <!-- Mocha css -->  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.css">
  <!-- Mocha dependency -->  <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.1.0/mocha.js"></script>
  <!-- Mocha: setup BDD -->  <script> mocha.setup('bdd'); </script>
  <!-- chai dependency -->  <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/2.0.0/chai.js"></script>
  <!-- export assert -->  <script>  var assert = chai.assert;  </script>
</head>

<body>
  <!-- script which should be tested -->  <script src="MyScript.js"></script>
  <!-- test itself -->  <script src="MyScriptTest.js"></script>
  <!-- element with id="mocha" for test results -->  <div id="mocha"></div>
  <!-- run tests! -->  <script>
    mocha.run();
  </script>
</body>
</html>

As you can see, mocha and chai libraries will be downloaded by SRIPT tag. Also we set up mocha for using BDD, exported "assert" for simple usage and executed mocha test running.
In addition, we need just 2 files:
<!-- script which should be tested --><script src="MyScript.js"></script>
<!-- test itself --><script src="MyScriptTest.js"></script>

- we will be creating them step-by-step during implementation. First - function for MyScript, next - testblock for that function in MyScriptTest.js.

3. Without closures.

First of all, for creating COUNTER functionality, we can try to use approach popular for other languages: just create an object for that:

function CounterObject() {
    this.currentValue = 0;

    this.inc = function () {
        return ++this.currentValue;
    }
}

Let's test it:
describe("CounterObject", function () {
    it("should be independent counters on every creation of counter object", function () {
        var counter1 = new CounterObject();
        assert.equal(counter1.inc(), 1);
        assert.equal(counter1.inc(), 2);

        var counter2 = new CounterObject();
        assert.equal(counter2.inc(), 1);
        assert.equal(counter2.inc(), 2);
    });

});


It's working! But unfortunately we have one vary bad thing here, developer console is returning:
>c = new CounterObject()
CounterObject {currentValue: 0}
    currentValue: 0
    function inc: ()

- beside inc() function we have access to currentValue variable as well. So everyone can just change it by re-assigning new value. We can not protect it from changing outside, because JavaScript doesn't have PRIVATE variable access. Let's create another test:
    it("should be possible to change current value because it unprotected at all", function () {
        var counter1 = new CounterObject();
        assert.equal(counter1.inc(), 1);
        assert.equal(counter1.inc(), 2);

        counter1.currentValue = 9;
        assert.equal(counter1.inc(), 10);
    });

Current value was changed and we can do nothing with that. So this approach will not work for JavaScript.

4. Safe counter with closures.

With new version of counter we are protected form direct variable changes:
function SafeCounter() {
    var currentValue = 0;
    return function () {        
         return ++currentValue;    
     }
}

>c = SafeCounter(): 
function() { return ++currentValue; }
- we have just one function inside "c" variable without access to local variable currentValue.


Tests:
describe("SafeCounter", function () {
    it("should be independent counters on every call of SafeCounter() function", function () {
        var counter1 = new Object();
        counter1.inc = SafeCounter();
        assert.equal(counter1.inc(), 1);
        assert.equal(counter1.inc(), 2);

        var counter2 = new Object();
        counter2.inc = SafeCounter();
        assert.equal(counter2.inc(), 1);
        assert.equal(counter2.inc(), 2);
    });
});


5. Extended version of safe counter. 

On previous step we created counted which fit our expectations, but we are returning only one function - so we can perform only one operation. Sometimes we may need more. It's possible to do that by returning an object:

function SafeExtendedCounter() {
    var currentValue = 0;

    return {        
          inc: function () {            
              return ++currentValue;        
          },        
          get: function () {            
              return currentValue;        
          },        
          reset: function () {            
              currentValue = 0;        
          }    
    };
}

Test:
describe("SafeExtendedCounter", function () {
    it("should be independent counters on every call of SafeExtendedCounter() function", function () {
        var counter1 = SafeExtendedCounter();
        assert.equal(counter1.inc(), 1);
        assert.equal(counter1.inc(), 2);

        var counter2 = SafeExtendedCounter();
        assert.equal(counter2.inc(), 1);
        assert.equal(counter2.inc(), 2);
    });

    it("should be GET function for getting current value", function () {
        var counter1 = SafeExtendedCounter();
        assert.equal(counter1.inc(), 1);
        assert.equal(counter1.get(), 1);
    });

    it("should be RESET function for reseting counter to zero", function () {
        var counter1 = SafeExtendedCounter();
        assert.equal(counter1.inc(), 1);
        assert.equal(counter1.inc(), 2);
        counter1.reset();
        assert.equal(counter1.get(), 0);
    });
});


6. Closures for "modules"(singleton objects)

Sometimes we may need a library or module with some functionality. Implementation should be hidden from outside and only interface functions should be visible. That's exactly what we created on previous step, but with the one exception: it's creating new object on every call, and it can consume a lot of resources. Sometimes it's better to have just one object implementation: "singleton" object.

We can implement that by creation on anonymous function :
(function() {......}), call it just after creation by "()" and assign it to variable:


var sayHelper = (function () {
    var name = "";
    var HI_MESSAGE = "Hi, ";
    var HELLO_MESSAGE = "Hello, ";
    return {
        setName: function (nameValue) {
            name = nameValue;
        },
        sayHi: function () {
            return HI_MESSAGE + name;
        },
        sayHello: function () {
            return HELLO_MESSAGE + name;
        }
    }
})();

Last "()" before ";" - for calling function bloc.

Now sayHelper is a singleton object. We can not create another instance, because function is anonymous, it has no name so we can not call it.


Test:
describe("sayHelper", function () {
    sayHelper.setName("Joe");
    it("should be [Hi, Joe] when we call sayHelper.sayHi()", function () {
        assert.equal(sayHelper.sayHi(), "Hi, Joe");
    });
    it("should be [Hello, Joe] when we call sayHelper.sayHello()", function () {
        assert.equal(sayHelper.sayHello(), "Hello, Joe");
    });
});


7. The end. 

In JavaScript closures used for making some resources "PRIVATE" and so on, it can be useful for modules/libraries. All source code can be downloaded from here.