Friday, January 29, 2016

GRADLE & NODE NPM - gradle task for execute npm install and bower install

https://gist.github.com/spikeheap/8558786

import org.gradle.api.tasks.Exec
defaultTasks 'bower'
// Get the path for the locally installed binaries
task npmBin << {
new ByteArrayOutputStream().withStream { os ->
def result = exec {
executable = 'npm'
args = ['bin']
standardOutput = os
}
ext.binPath = os.toString().trim() + "/"
}
}
// Install packages from package.json
task npm(type: Exec) {
description = "Grab NodeJS dependencies (from package.json)"
commandLine = ["npm", "install"]
inputs.file "package.json"
outputs.dir "node_modules"
tasks.npmBin.execute()
}
// Install the bower components for front-end library management
task bower(dependsOn: 'npm', type: Exec){
commandLine "${npmBin.binPath}bower", 'install'
}

JAVASCRIPT vs ANGULARJS - copy object by value, not by reference

In JavaScript copy of object is done by reference:
var newObj = Object.create(oldObj); //Modification in newObj would be reflected in oldObj.

JavaScript solution 1: Inline deep copying (if you know its structure)
var newObj = {
   name: source.name,
   type: source.type
}

JavaScript solution 2: Use JSON parse (it could be more slower)
var newObject = JSON.parse(JSON.stringify(oldObject));

Angular way:
var newObject = angular.copy(oldObject);

WINDOWS - port, process PID tracking with CurrPorts application

If you need to track on WINDOWS which process PID is running on which port, consider to use:
CurrPorts (CPorts) application:
http://www.download3k.com/Install-CurrPorts.html

JAVASCRIPT - JavaScript the Good Parts by Douglas Crockford (my notes)

EQUALS = = =
Always use = = = ,never = =

SCOPE
JavaScript has function scope, not block scope. The use of 'var' keyword could be confusing in it.

Declare all variables at the top of the function.

GLOBAL VARIABLES
Global variables are evil.
Avoid global variables.
When using it, be explicit and use UPPER_CASE

var a = b = 0 // it is confusing
It does not means var a = 0, var b = 0
It means you've created local a and global b:
b = 0;
var a = b;

INCREMENTATION Use x += 1 instead of x++

BRACKETS
Always put curly brackets on the right of statement etc.
e.g.
return { //OK
};
return 
{ //syntactic error in JS
};

Always put the curly braces on!
if (a) (b); (c); // Creates confusion
if (a) { (b); (c); } //result 1 OK
if (a) { (b) }; (c); //result 2 OK


"Premature optimization is the root of all evil"Donald Knuth
Only optimize the code that is taking a lot of the time.

NEW
Don't use the 'new' keyword for an object creation.

FOR
In 'for' loop over the objects properties you need to check that this property is the one that belongs to the the object and not to its prototype:

for (name in object) {
    if (object.hasOwnProperty(name)) {
        ...
    }
}

But... the 'hasOwnProperty' is not the statement, but function, so it needs to have an extra safe call on prototype. This is HORRIBLE, but it is the most reliable way do it:

for (name in object) {
    if (Object.prototype.hasOwnProperty.call(object, name)) {
        ...
    }
}

ARRAYS
Use splice instead of delete if you need to remove from an array.
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; //['a', undefined, 'c', 'd']
myArray.splice(1, 1); //['a', 'c', 'd']
myArray.splice(1, 1); //start from index 1 and delete 1 element
Splice will be slow because it will move each element in order to fill an empty place...

ARRAYS vs OBJECTS
Use objects when the names are arbitrary strings
Use arrays when the names are sequential integers

NULL and UNDEFINED
All values are objects except null and undefined.
Don't store undefined in the object, it's confusing (like is it was declared and not defined?)

TYPEOF
array and null are 'object'
Use Arraye.isArray([]); //true

FALSY VALUES
false
null
undefined
"" (empty string)
0
NaN

REFERENCE
Objects are passed by reference, not by value
The = = = compares object refs, not values!!!

STRINGS to NUMBERS
+"42" = = = 42
Number("42") = = = 42
parseInt("42", 10) = = = 42
+"3" + (+"4") = = = 7

&&
if (a) {
    return a.member;
} else {
    return a;
}
It is the same as:
return a && a.member

SWITCH
Switch value can be a string
Case values can be expressions

FUNCTION
Function statement (or declaration) - if the first token in a statement is function, then it is a function statement.

function foo() {}
expands to:
var foo = function foo() {};
which fother expands to:
var foo = undefinded; //it was hoisted
foo = function foo() {};

RETURN
Return statement - if there is no expression, then the retrun value is undefined 

PARAMETERS

Pseudo parameters - each function receives are arguments ans this there is no expression.
Arguments - an array like object (it is not an array) of all parameters that were passed to the function.
arguments.length // is a number of all arguments

Extra arguments ignored, Missed arguments will be undefined.

4 ways to call a function:
Function form (bound to the global object, fixed in ES5/strict, in ES6 to undefined)
functionObject(args)
Method form (bound to this of object)
thisObject.methodName(args)
thisObject["methodName"] (args)
Constructor form
new FunctionObject(args)
Apply form
functionObject.apply(thisObject, [args])

An inner function does not get access to the outer this. Work around:
var that = this; //this allows to inner function get reference to outer this of the function

function factorial(n) {
    return (function foo(result) { //result is the 1 passed in IIFE parameter
        while (n > 1) { //IIFE copy n value and operates with it on its own scope
            result *= n;
            n -= 1;
        }
        return result;
    })(1);
}
CLOSURE
Context of an inner function includes the scope of the outer function.
An inner function enjoys that context even after the parent functions have returned.
var digit_name = (function () {
    var names = ['zero', 'one', 'two', 'three']; //dies immediately after execution
    return function (n) { //closure remains as a digit_name
        return names[n];
    };
})();
digit_name here would be equal of IIFE return function:
    function (n) { //it is a closure, that remember array names[] of outer IIFE scope
        return names[n];
    };
There is mistake on definition on the image above:
In fact, outer function here is outer() and it cannot see y of inner function inner().
Inner function inner() can see the both a and y.
MONADS (macroid)
function MONAD() {
    return function unit(value) {
        var monad = Object.create(null);
        monad.bind = function (func) {
            return func(value);
        };
        return monad;
    } 
}
var unit = MONAD();
var monad = unit("Hello World!");
monad.bind(alert);
Improving Monads:
Now you can call alert method by two different ways:
monad.bind(alert);
monad.alert();
Usually ajax() method takes remote data and use it in some function like this:
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({url: "demo_test.txt", success: function(result){
            $("#div1").html(result);
        }});
    });
});
Maybe Monads
One of the use is check for NPE:
TURN BASED PROCESSING INSTEAD OF THREADS
Never wait, never block, finish fast
Threads causes races, Mutual Exclusion causes dead locks 
PROMISE: Promise Monads
Promise is event generator.

In this example the use of failure is the better way to handle errors then throwing exceptions on try/catch block, cause it keeps stack full.
my_promise.when(a).when(b).when(c, failure)



https://github.com/douglascrockford/monad

Identity Monad
//    var identity = MONAD();
//    var monad = identity("Hello world.");
//    monad.bind(alert);
Ajax Monad
// var ajax = MONAD() // .lift('alert', alert); // var monad = ajax("Hello world."); // monad.alert();
Maybe Monad
// var maybe = MONAD(function (monad, value) { // if (value === null || value === undefined) { // monad.is_null = true; // monad.bind = function () { // return monad; // }; // return null; // } // return value; // }); // var monad = maybe(null); // monad.bind(alert); // Nothing happens.

VIDEO TO WATCH:
Carl Hewitt. The Actor Model (everything you wanted to know, but were afraid to ask )
Mark Miller (authore of Promise model). Secure Distributed Programming with Object-capabilities in JavaScript

TypeScript
TypeScript was developed by Microsoft to make Visual Studio work better with JavaScript. )))
TypeScript generates very good quality JavaScript code (many other transpilers dont)
Typed JS like TypeScript does not decrease the amount of tests you need to write to be sure there is no errors connected with types. So it is almost vain trade-off.
It is not a Typesystem it is annoying.
Lisp developed the most difficult system without of types...
His JSLint will not work with TypeScript

JAVASCRIPT - the use of double and triple equals "===" vs "=="

The rule for use of  triple an double equals in JavaScript is simple:
Always use = = = and never = =
(Always use triple equals and 
never double equals)

JAVASCRIPT - a good resources provided by Douglas CrockFord (a link)

http://www.crockford.com/

Saturday, January 23, 2016

ANGULARJS - clean code patterns from John Papa

Tools:
WebStorm (prefered), Sublime, Visual Studio, Brackets, Atom

Repository:
https://github.com/johnpapa/ng-demos

Principles:
Separation of Concerns: 1 Component, 1 Role, 1 File
LIFT:
Locating our code is easy
Identifying code at a glance
Flat structure as long as we can
Try to stay DRY

Advance JavaScript by Kyle Simpson (my notes)

Kyle Simpson
https://www.patreon.com/getify?ty=h

https://developer.mozilla.org/en-US/docs/Web/JavaScript
http://www.ecma-international.org/ecma-262/6.0/index.html
https://github.com/rwaldron/idiomatic.js

https://en.wikipedia.org/wiki/Just-in-time_compilation
JIT compilation - just-in-time (JIT) compilation, also known as dynamic translation, is compilation done during execution of a program – at run time – rather than prior to execution.

Compiler terminology:
LHS - left hand side for an assignment
RHS - right hand side for an assignment
var foo = 'bar'
var foo here is LHS reference an it is TARGET
'bar' is RHS reference and it is a SOURCE

Scope
function baz(foo) {
     foo = 'bam';
     bam = 'yay'
}

foo here would be the local scope variable created in compile time
bam in NO STRICT mode will be created as a global variable during run time, cause in local scope it will not be founded.
bam in STRICT mode will produce error because bam never was created either in local or global scope. 
This happen because declaration in JS goes only with VAR or FUNCTION words
Undeclared variable means we unable to find proper LHS reference in any of the scopes that we have access to. 

In JS undeclared and undefined are totally different words.

Undefined variable - variable that was declared, but has special empty value that was mistakenly named in JS as undefined (should be named with better word). 
Undefined is an actual real value for empty value, it is a type. (e.g. there cannot be a vacuum where value exist)

bar(); it is RHS because... it is not LHS :) (it has not '=' sign)


function baz(foo) {
     var foo = 'bam';
     bam = 'yay'

     finction bam() {
        var baz = 'bla';
     }

     bam();
}

bam(); if this function would be called from global scope it will produce reference error

FUN http://my-fly.ru/blog/43082783722/Retsept-schastlivoy-zhizni-po-odesski 

There could be only two cases: 
OR Function Declaration: (if the 'function' word is the the very first word in the statement)
function bar() {

OR Function Expression: (the 'function' word is NOT the first word in the statement)
var bla = function bar() {
}
bar(); //will result in ERROR if it is called outside of local scope

ALWAYS use Named Function Expression instead of Anonymous. 
It results in 3 advantages:
- it gives self reference inside the local scope
- it allows debugging the function
- its name gives description for what it is doing

EVAL keyword is a way of cheating compiler, making it think that parameter of eval was created before. For instance:

var bar = 'bar';
 
function foo(str) {
    eval(str); //cheating
    console.log(bar); //it will print 42, not 'bar'
}

foo('var bar = 42;');

NEVER use 'eval' as well as 'with' statement (even if the strict mode does create for it new scope)

I I F E pattern
The IIFE term was invented by Ben Alman ('Cowboy') http://benalman.com/
IIFE sometimes rendered as “self-executing anonymous function” (or self-invoked anonymous function) 
I I F E - Immediately Invoked Function Expression 
The most widely accepted way to tell the parser to expect a function expression is just to wrap it in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
http://benalman.com/news/2010/11/immediately-invoked-function-expression/

CLOSURE (First-class functions)
Closure is when a function 'remembers' and access its lexical scope even when the function is executed outside that lexical scope.


http://skilldrick.co.uk/2011/04/closures-explained-with-javascript/
https://en.wikipedia.org/wiki/Closure_%28computer_programming%29
https://en.wikipedia.org/wiki/First-class_citizen

Any function defined inside another function can access the outer function’s passed-in arguments and variables (this relationship is known as a closure)
http://benalman.com/news/2010/11/immediately-invoked-function-expression/
A closure is a function called in one context that remembers variables defined in another context – the context in which it was defined.
http://skilldrick.co.uk/2011/04/closures-explained-with-javascript/



SCOPE
Lexical scope - has author scope (JavaScript)
Dynamic scope -  has run time (Bash)
Scope can be created by:
- Functions
- Curly braces and keyword let
- Try and catch block


Cheating scope by eval and with keywords.

HOISTING
It is invented terme to explain how JS works.
Function hoisted first, before variables.
Keyword let is not hoisted.

THIS
Every function, while executing, has a reference to its current execution context, called THIS

4 Binding Rules of THIS by order. Rules of precedence by Call Side:
- Default binding rule:
In strict mode of current function this = Undefined value, else = global object

- Implicit binding rule:
function foo() { console.log(this.bar) } 
var bar = 'bar';
var o2 = { bar: 'bar2', foo: foo};
foo(); //bar
o2.foo(); //bar2 it is implicit binding

- Explicit binding rule: use of call or apply in call side with object in its parameter.
bar.call(obj) - use this of passed in param obj.
Hard explicit binding is encapsulate bar.call(obj) in IIFE

By NEW binding
- Create new object
- Link this new object with other object
- New object bound to THIS for the purposes of the function call
- Implicitly insert at the end of function return this; if no other return is provided.

Classic Module Pattern
- It must be executed in the outer wrapper function (not necessary IIFE)
- One or more function that get returned from that function call

Principle of Least Privilege, or Least Exposure (make everything private and only expouse what needs to be public e.g. executing foo.bar(); // bar)
The object of return is public API of module. Inside is its private encapsulated data.
var foo = (function () {
    var o = { bar: 'bar' };  
    return {
         bar: function() {
              console.log(o.bar);
         }
   }
})();
foo.bar(); //bar 


Modified Module Pattern (much more organized)
It is better use object variable instead of anonymous function. It can be updated in run time.
var foo = (function () {
    var publicAPI = {
      bar: function() {
           publicAPI.baz();
      },
      baz: function() {
           console.log('baz');
      }
    }
   return publicAPI;
})();
foo.bar(); //baz 

Module Pattern in ES6
It is better use object variable instead of anonymous function. It can be updated in run time.
E.g. module goes in separate foo.js file:
var o = { bar: 'bar' };
export function bar() {
    return o.bar;
}

From other test.js file:
import bar from 'foo'; //will import just one function from that module 
bar(); //bar 

module foo from 'foo';
foo.bar(); //bar 


Object Orienting
A constructor makes an object linked to (not to be 'based on') its own prototype.

PROTOTYPE
__proto__ is a public link to the internal property of [[ prototype ]] . It is pronounced as kind of 'donedoproto', It was invented by Mozilla and supported for all other browsers except... IE till the version 11 (Edge).
__proto__ became standard only since ES6.
[[ prototype ]] . Is a linkage from one object to another.





var a1 = new Foo('a1');
a1.__proto__ //even in IE
a1.__proto__ === Object.getPrototypeOf(a1); //prior to IE 11
a1.__proto__ === a1.constructor.prototype; //always available, but it is writable function

Using polymorphism avoid shadowing of properties names of object and its prototype.

Objects Linked

function Foo(who) {
    this.me = who;
}

function Bar(who) {
    Foo.call(this, who); //way 1
}

Bar.prototype = Object.create(Foo.prototype); //way 2

Inheritance vs. Behavior delegation
var a1 = new Foo();
Foo.prototype.speak = function....
a1.speak() //this is Behavior delegation from object to its prototype (it is not by copying)

OLOO pattern
Object Linked Other Object



Async callbacks

Generators in ES6
It is a new kind of function: function*
It can stop on keyword yield
It can return kind of iterator
yield null - its a kind of way to send messages to the generator.
Its a two way passing messages mechanism.
It should eliminate Promises and callbacks.



This example shows how generators could work asynchronous way, 
even if it looks like synchronous.


Combination of Generators and Promises is the future!

No Threads just Shared Memory with Events Loop