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/