JS (ES5, ES6, ES7) is @angular/core technology

Saturday, December 31, 2016

javascript in client, server, database, node_modules, addons, cloud

Open Source Rules!

future technologies (the world is yours):


attitude, facts and mission ...

we are fearless, ruthless and honest, the goal is progress. we are constantly focused on our goal, produce quality working software as fast as possible. we are open source.


Numbers in JavaScript are double precision 64-bit format IEEE 754 values

                    
                                                //javascript rocks
//addition
const sum = 0.1 + 0.2; //0.30000000000000004
//built in math object
const pow = Math.pow(2, 8); //256
const sin = Math.sin(4.1); //-0.8182771110644103
//convert string to int using built in parseint function
const convertMyNumber = parseInt("12345678", 10); //12345678
const convertMyNumber1 = parseInt("0100", 10); //100
const octal = parseInt(010); //8
const hexadecimal = parseInt(0x10) //16
//convert binary to integer, use base of two
const binary = parseInt(111, 2); //7
//use unary + operator to convert values to numbers
const val1 = +"1001"; //1001
const val2 = +"0100"; //100
const val3 = +"0x10"; //16
//special value NAN is returned if string is non-numeric
const notANumber = parseInt("hello", 10); //NaN
//test for is NAN
const isNan = isNaN(NaN); //true
//javascript has special values infinity and -infinity
const isInfinity = 1 / 0; //Infinity => [(ing luv ug)]
const isNegativeInfinity = -1 / 0; //-Infinity
//test for infinity, -infinity and NAN values using built-in isFinite function
const finite1 = isFinite(1/0); //false
const finite2 = isFinite(-1/0); //false
const finite3 = isFinite(NaN); //false
console.log(finite3);

                        
                    

Strings in JavaScript are sequences of Unicode Characters, UTF-16

                    
                                                  //javascript rocks
//length property
const hello = "hello carmen".length; //12
const iC = "hello carmen".charAt(6); //c
const rePlace = "hello carmen".replace("hello", "i love u,"); //i love u, carmen
const uC = "hello carmen".toUpperCase(); //HELLO CARMEN
//boolean values true and false. false, 0, empty strings, NaN, null, and undefined all become false
//all other values become true
const a = Boolean(1); //true
const b = Boolean(true); //true
const c = Boolean(123); //true
const d = Boolean(""); //false
//new variables in javascript declared using let, const or var
//let block level variable, available from function block it is enclosed in
let myCodeName = "warlord";
const targetArray = ['X', 'A', 'Z', 'R', 'E']
for (let i = 0; i < targetArray.length; i++) {
    console.log(targetArray[i]); //XAZRE
}
//const allows you to declare a variable whose values are never intended to change
const Pi = 3.14 //variable Pi is set 
//Pi = 1; throws an error because constant variable
//var is most common declarative keyword, it has no restrictions and globally accessible
var e;
var f = "function";
for (var myVarVariable = 0; myVarVariable < 3; myVarVariable++){
    console.log(myVarVariable); //0 1 2
}
console.log(myVarVariable); //3
                        
                    

Operators, type coercion, control structures

                    
                                                //javascript runs on nodejs and v8 javascript engine
//Operators
let x = 10; //110
const y = x += 100; //110
const z = x + 100; //210
//+ operator concatenates strings
const helloWorld = "hello " + "world"; //hello world
const add = "7" + 8 + 7; //787
const add1 = 7 + 8 + "7"; //157
//double equals performs type coercion
const tcns = 12345 =="12345"; //true
const tcnb = 1 == true; //true
//to avoid type coercion,make sure comparisons are always accurate, always use triple equals operator
const ntcns = 12345 === "12345"; //false
const ntcnb = 1 === true;
//control structures if else chaining
var myName = "puppy";
if (myName === "puppy"){
    myName += "*****";
} else if (myName === "kitten"){
    myName += "*****";
} else {
    myName = "!" + myName;
}
console.log(myName); //puppy*****
//while loops, while good for basic looping do while executes at least once
while(true){
    //infinite loops
    console.log("code, exercise, eat, sleep, read more code, write more code ...")
}
let i = 0;
do {
    console.log(i++);
} while (i <= 10);
                        
                    

For loops, operators, switch

                    
                                                //javascript rocks
//for loops
for (let i = 0; i < 5; i++){
    console.log(i); //0 1 2 3 4
}
let array = ['A', 'B', 'C', 'D', 'E'];
for (let value of array){
    console.log(value); //A B C D E
}
let object = { a: 1, b: 2, c: 3}
for (let property in object){
    console.log(property); //a b c
}
//the && and || operators short-circuit logic whether second operand is executed is dependent on first
let o = { getName(){return "marry";}}
let name = o && o.getName(); //marry
//or for setting default values
let otherName = null;
let name1 = otherName || "default"; //default
let age = 32;
let allowed = (age > 18) ? "yes" : "no"; //yes
//switch statement can be used for multiple branches based on number or string
let a = 'code';
switch(a){
    case 'draw':
    a = 'draw it';
    break;
    case 'eat':
    a = 'eat it';
    break;
    case 'code':
    a = 'code it';
    break;
    default:
    a = 'read it';
}
console.log(a); //code it
                        
                    

Fallthroughs, objects

                    
                                                //javascript rocks
//fallthroughs don't add a break, falls through to next level
let a = 2;
switch(a){
    case 1: //fallthrough
    case 2: //fallthrough
    case 3:
    console.log('eat it'); //eat it
    default:
    'doSomething';
}
//Objects
let obj = new Object();
let obj1 = {}; //object literal syntax
//initialize object in its entirety
let obj2 = {
    name: "medal",
    "for": "mick",
    details: {
        color: "rainbow",
        size: 33
    }
}
console.log(obj2.details.color); //rainbow
console.log(obj2["details"]["size"]); //33
//create object protototype, Person and instance of that person, you ...
function Person(name, age){
    this.name = name;
    this.age = age;
}
//define an object
let you = new Person("you", 25);
console.log(you.name); console.log(you.age); //you 25
//once created an object's properties can again be accessed in one of two ways
obj2.name = "Igor";
let name = obj2.name;
console.log(name); //Igor
//and ...
obj2["name"] = "Misko";
let name1 = obj2["name"];
console.log(name1); //Misko
obj2["for"] = "Simon";
console.log(obj2["for"]); //Simon
                        
                    

Arrays, hip hip Array

                    
                      //javascript rocks runs on nodejs powered by v8 javascript engine google os technology
//arrays are special type of object, with one magic property called length
let a = new Array();
a[0] = "puppy";
a[1] = "kitten";
a[2] = "tiger";
a[3] = "lion";
a[4] = "wolf";
let len = a.length; //5
//array literal
let a1 = ["puppy", "kitten", "tiger", "lion", "wolf"];
let len1 = a1.length; //5
//length of array is one more than highest index
a1[100] = "blitzkrieg";
let len2 = a1.length; //101
//query non existant array index, get value of undefined returned
typeof a[90]; //undefined
for (let i = 0; i < a.length; i++) {
    a[i]; //puppy kitten tiger lion wolf
}
a.forEach((currentValue, index, array) => {
        `${index} : ${currentValue} : ${array[index]}`; 
        //0 : puppy : puppy 1 : kitten : kitten 2 : tiger : tiger ...
});
//add one or more items to end of array
a.push("jaguar"); //puppy ... jaguar
//returns a string with the tostring() of each element separated by commas
let ret = a.toString();//puppy,kitten,tiger,lion,wolf
//same as above except localized
let ret1 = a.toLocaleString();
//returns a new array with items added on to it
let ret2 = a.concat(['leopard','crocodile']); //['puppy', ..., 'leopard', 'crocodile']
//converts array to string with values delimited by separator param in parentheses
let ret3 = a.join('|'); //puppy|kitten|tiger|lion|wolf|jaguar
//removes and returns the last item
let ret4 = a.pop(); //jaguar returned and is removed from array
//reverse the array
let ret5 = a.reverse(); //['wolf', 'lion', ..., 'puppy']
//removes and returns the first item
let ret6 = a.shift(); //wolf returned and is removed from array
//returns a subarray
let ret7 = a.slice(1, a.length); //['tiger','kitten','puppy']
//sorts asc default takes optional comparison function
let ret8 = a.sort(); //['kitten', 'lion', 'puppy', 'tiger']
//modify array by deleting a section and replacing it with more items
a.splice(a.indexOf('lion', 0), 1); //['kitten','puppy', 'tiger']
//prepends items to start of array
a.unshift('wifi'); //['wifi', 'kitten','puppy', 'tiger']
                        
                    

Functions

                    
                                                //javascript rocks
//functions
function multiply(a, b){
    const total = a * b;
    return total;
}
//arguments additional function argument array like object holding all values passed to function
function calculateAverage(){
    let sum = 0;
    for (let i = 0; i < arguments.length; i++){
        sum += arguments[i];
    }
    return sum / arguments.length;
}
//spread operator ...[variable] includes within variable entire list of uncaptured arguments function
//was called with
function average(...args) {
    let sum = 0;
    for (let value of args){
        sum += value;
    }
    return sum / args.length;
}
function averageArray(arr){
    let sum = 0;
    for (let i = 0; i < arr.length; i++){
        sum += arr[i];
    }
    return sum / arr.length;
}
//anonymous function
let a = function() {
    let sum = 0;
    for (let i = 0; i < arguments.length; i++){
        sum += arguments[i];
    }
    return sum / arguments.length;
}
//recursive, anonymous, arrow operator function
const factorial = (n) => { return (n <= 0) ? 1 : n * factorial(n - 1);};
                        
                    

Custom objects, prototype, closures

                    
                                                //javascript rocks
//custom objects prototype chain, anything assigned to prototype becomes available to all
//instances of constructor via the this object
function Robot(first, last){
    this.first = first;
    this.last = last;
}
Robot.prototype.fullName = function() {
    return `${this.first} ${this.last}`;
};
Robot.prototype.fullNameReversed = function() {
    return `${this.last} ${this.first}`;
};
let r = new Robot('nils', 'naegele');
Robot.prototype.firstNameCaps = function() {
    return this.first.toUpperCase();
};
//add things to prototype of built in javascript objects
String.prototype.reverse = function reverse() {
    let rev = '';
    for (let i = this.length - 1; i >= 0; i--) {
        rev += this[i];
    }
    return rev;
}
'clp u are beautiful'.reverse();
//redefine tostring
let r1 = new Robot('flash', 'light');
Robot.prototype.toString = function() {
    return `|robot: ${this.fullname()}|`
}
//apply and rest arguments
function trivialNew(constructor, ...args){
    let o = {};
    constructor.apply(o, args);
    return o;
}
//virtually identical
let brecht = trivialNew(Robot, 'brecht', 'willy');
let brecht1 = new Robot('brecht', 'willy');
//apply sister function call let's you set this takes in expanded argument list as opposed to an array
function lastNameCaps() {
    return this.last.toUpperCase();
}     
let r2 = new Robot("mick", "long");
lastNameCaps.call(r2);
//closures, function defined inside another function has access to outer function's variables
function makeMultiplier(a) {
    return function(b){
        return a * b;
    };
}
let x = makeMultiplier(10);
let y = makeMultiplier(11);
console.log(x(10)); //100
console.log(y(10)); //110
                        
                    

Async await

                    
                                                //javascript rocks
//async function called, it returns a promise
function resolveAfter3Seconds(x){
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(x);
        }, 3000);
    });
}
async function add(x){
    let a = resolveAfter3Seconds(20);
    let b = resolveAfter3Seconds(30);
    return x + await a + await b;
}
add(30).then(v => {
    console.log(v); //prints 80 after 3 seconds
});
async function add1(x) {
    let a = await resolveAfter3Seconds(30);
    let b = await resolveAfter3Seconds(40);
    return x + a + b;
}
add1(30).then(v => {
    console.log(v); //prints 100 after 6 seconds
});

                        
                    

Classes, extends, super

                    
                                                //javascript rocks
//class declaration creates a new class with a given name using prototype based inheritance
class Human {
    constructor(height, weight){
        this.name = 'Humanoid';
        this.height = height;
        this.weight = weight;
    }
}
class Robot extends Human {
    constructor(height, weight){
        super(height, weight);
        this.name = 'Android';
    }
}
let r = new Robot(100, 50); //Android 100 50
//static keyword defines a static method for a class
class Quadruple {
    static quadruple(n){
        if (n === undefined){
            n = 1;
        }
        return n * 4;
    }
}
class BiggerQuadruple extends Quadruple {
    static quadruple(n){
        return super.quadruple(n) * super.quadruple(n);
    }
}
console.log(Quadruple.quadruple()); //4
console.log(Quadruple.quadruple(6)); //24
console.log(BiggerQuadruple.quadruple(4)); //256
                        
                    

Arrows, lexical this

                    
                                                //javascript rocks
//arrow functions and lexical this
const evenNumbers = [2, 4, 6, 8, 10];
const odds = evenNumbers.map(v => v + 1);
const evens = evenNumbers.map(v => v);
const numbers = evenNumbers.map((v, i) => v + i);
let eights = [];
//statement bodies
numbers.forEach( v => {
    if (v % 8 === 0){ eights.push(v);}
});
let linu = {
    name: 'linu',
    friends: ['androia', 'ubunta', 'fadora', 'sierra', 'wifi'],
    displayFriends(){
        this.friends.forEach(v => console.log(`${this.name} greets ${v}`));
    }
};
console.log(linu.displayFriends());
//lexical arguments
function power3() {
    let sample = () => {
        let numbers = [];
        for (let number of arguments){
            numbers.push(Math.pow(number, 3))
        }
        return numbers;
    };
    return sample();
}
console.log(power3(10, 8, 6, 4)); //[1000, 512, 216, 64]
                        
                    

Includes, generators, destructuring

                    
                                                //javascript rocks
//determines whether an array includes a certain element returning true or false as appropriate
const a = [1, 2, 3, 4, 5];
console.log(a.includes(1)); //true
console.log(a.includes(2)); //true
console.log(a.includes(6)); //false
console.log(a.includes(5, 5)); //false
const uint8 = new Uint8Array([1, 2, 3, 4, 5]);
const a1 = uint8.includes(1); //true
const a2 = uint8.includes(5, 4); //true
const a3 = uint8.includes(3, 1); //true
console.log(a3);
//generators are functions which can be exited and later re-entered. their context(variable bindings)
//will be saved across reentrances
function* logGenerator() {
    console.log(yield);
    console.log(yield);
    console.log(yield);
}
let gen = logGenerator();
//first call of next executes from start of function until the first yield statement
gen.next();
gen.next('just angular');
gen.next('california');
gen.next('global');
//rest parameter syntax ...args allows represent an indefinite number of arguments as an array
//rest parameters can be destructured, data can be extracted into distinct variables
function fun(...[a, b, c, d]){
    return a + b + c + d;
}
let f = fun(1); //NaN
let f1 = fun(1, 2, 3, 4); //10
let f2 = fun(1, 2, 3, 4, 5); //10
//get count of args by using length property
function fun1(...args){
    console.log(args.length);
}
fun1(); //0
fun1(1); //1
fun1(1, 2, 3); //3
                        
                    

Rest parameters, object.values(), object.entries()

                    
                                                //javascript rocks
//use rest parameters to collect arguments from second one to end, then multiply by first
function multiply(msR, ...args){
    return args.map((x) => { return msR * x;});
}
const arr = multiply(2, 2, 4, 8, 10);
console.log(arr); //[4, 8, 16, 20]
function sortArgs(...args){
    let sortedArgs = args.sort();
    return sortedArgs;
}
console.log(sortArgs(9, 7, 3, 5, 1, 2)); //[1, 2, 3, 5, 7, 9]
//object.values() returns an array whose elements are the enumerable property
//values found on the object
const obj = { v1: "honesty", v2: "progress"};
console.log(Object.values(obj)); // ['honesty', 'progress']
//array like object
const obj1 = { 0: 'fearless', 1: 'ruthless', 2: 'honest', 3: 'goals', 4: 'progress' };
console.log(Object.values(obj1));
//array like object with random key ordering
const obj2 = { 150: 'achievement', 10: 'success', 77: 'progress', 41: 'health', 200:'performance' };
console.log(Object.values(obj2));
//non-object arguments will be coerced to an object
console.log(Object.values("eval")); //['e', 'v', 'a', 'l']
//object.entries() returns an array whose elements are arrays corresponding to the enumerable property
//key value pairs found directly upon object
const obj3 = {a: 'honor', b: 'integrity', c: 'purity', d: 'honesty'};
console.log(Object.entries(obj3)); //[ [ 'a', 'honor' ],[ 'b', 'integrity' ],[ 'c', 'purity' ],[ 'd', 'honesty' ] ]
//array like object with random key ordering
const obj4 = { 100: 'a', 90: 'b', 80: 'c'};
console.log(Object.entries(obj4)); //[ [ '80', 'c' ], [ '90', 'b' ], [ '100', 'a' ] ]
//iterate through key-value gracefully, is the spirit of node
const obj5 = {a: 5, b: 7, c: 9};
for (let [key, value] of Object.entries(obj5)){
    console.log(`${key} ${value}`); // a 5 b 7 c 9
}
                        
                    

Default Success Warning Important Info Inverse
B S W I ? O