Thursday, November 3, 2016

require.js first steps

Very often, we have to split a solid application to the set of simple modules. And of course, such modules can have dependencies. In such situations we have to manage dependencies somehow. For example we can have module A which is using modules B and C. And module B use modules D and E. So we have to load this modules in order:
  <script src="js/E.js"></script>
  <script src="js/D.js"></script>
  <script src="js/B.js"></script>
  <script src="js/C.js"></script>
  <script src="js/A.js"></script>

RequireJS - one of the tools for managing such situations. Using is we will have just to load main file and requirejs itself:
<script data-main="js/A"  src="http://requirejs.org/docs/release/2.3.2/comments/require.js"></script>


Let's create a simple application without require.js and after that let's re-write it with it.
In our application we will have 2 entities: User and Department. 2 tools: Validator and Logger. And main file which is using them all.

1. Without require.js. 

We are just creating separate js files and after all w will have to list them in proper order in html file.

1.1 User object 

function User(id, name) {
  this.id=id;
  this.name=name;
  this.toString = function() {
     return name;
  }
}


1.2 Department object

function Department(id, name) {
 this.users=[];
 this.id=id;
 this.name=name;

 this.addUser = function(user) {
   this.users.push(user);
 };

 this.getUsers = function() {
   return this.users;
 };
 
}


1.3 Validator object 

function hasAttribute(object, attribute) {
   return object.hasOwnProperty(attribute);
}

function isValid(object) {
  return hasAttribute(object, "name") && hasAttribute(object, "id");
}



1.4 Logger

function idNameFormat(object) {
  return "["+object.id+"]"+object.name;
}

function logUser(user) {
  console.log("user:"+idNameFormat(user));
}

function logDepartment(department) {
  console.log("department:"+idNameFormat(department)+" users:"+department.getUsers().toString());
}


1.5. Main script

We are just creating several objects, validating them and printing them using logger. 

function run() {
   var user1=new User(1, "Joe");
   var user2=new User(2, "Black");

   var dep1=new Department(1, "IT");
   dep1.addUser(user1);
   dep1.addUser(user2);

   if (isValid(user1) && isValid(user2) && isValid(dep1)) {
      logUser(user1);
      logUser(user2);
      logDepartment(dep1);
   } else {
      console.log("errors in validation");
   }
   
}

1.6 HTML file 

All our modules has to be listed in a proper order otherwise our application will not work.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
</head>

<body>

  <script src="js/validator.js"></script>
  <script src="js/user.js"></script>
  <script src="js/department.js"></script>
  <script src="js/logger.js"></script>
  <script src="js/main.js"></script>
  
  <script>
    run();
  </script>
</body>

</html>


2. Now let's rewrite application using require.js

2.1. User

We are defining User function and returning it.

define(function () {

    function User(id, name) {
        this.id = id;
        this.name = name;

        this.toString = function () {
            return this.name;
        };
    }

    return User;
});


2.2. Department

The same as with User.

define(function () {

    function Department(id, name) {
        this.users = [];
        this.id = id;
        this.name = name;

        this.addUser = function (user) {
            this.users.push(user);
        };

        this.getUsers = function () {
            return this.users;
        };
    }

    return Department;

});

2.3 Validator

Here we have private method "hasAttribute" and public method "isValid".

define(function () {

    function hasAttribute(object, attribute) {
        return object.hasOwnProperty(attribute);
    }

    return {
        isValid: function (object) {
            return hasAttribute(object, "name") && hasAttribute(object, "id");
        }
    }

});


2.4 Logger

Here we also have private method and 2 public methods.

define(function () {
        function idNameFormat(object) {
            return "[" + object.id + "]" + object.name;
        }

        return {
            logUser: function (user) {
                console.log("user:" + idNameFormat(user));

            },
            logDepartment: function (department) {
                console.log("department:" + idNameFormat(department) + ". users:" + department.getUsers().toString());
            }
        }
    }
);


2.5 Main

Here we have most interesting thing: we are getting dependencies using require.js

require(["user", "department", "logger", "validator"], function (User, Department, Logger, Validator) {
    console.log("Hello world!");

    var user1 = new User(1, "Joe");
    var user2 = new User(2, "Black");

    var dep1 = new Department(1, "IT");
    dep1.addUser(user1);
    dep1.addUser(user2);

    if (Validator.isValid(user1) && Validator.isValid(user2) && Validator.isValid(dep1)) {
        Logger.logUser(user1);
        Logger.logUser(user2);
        Logger.logDepartment(dep1);
    } else {
        console.log("errors in validation");
    }


});


2.6. HTML file

Here we just have to point to our main file ("js/main.js"  - file ending ".js" can be omitted) and path to require.js(url).


<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
</head>

<body>

  <script data-main="js/main"  src="http://requirejs.org/docs/release/2.3.2/comments/require.js"></script>

</body>

</html>

3.  Execution.


logger.js:8 user:[1]Joe
logger.js:8 user:[2]Black
logger.js:12 department:[1]IT. users:Joe,Black

4. The end. 

Development with  RequireJS makes part of application modular and reusable.

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.