Thursday, October 19, 2017

JavaScript Modules

Singleton Pattern

Immediately Invoked Function Expression (IIFE) returns an object that contains references to the public API of the module.

displayName function-scoped variable serves as the data member and retains its value as a result of function closure.

var myModule = (function(){
    var displayName

    function setName(name){
        displayName = name
    }

    function printName(){
        console.log('Hello ' + displayName)
    }

    return{
        setName : setName,
        printName : printName
    }
})()

myModule.setName('Bob')
myModule.printName()

Hello Bob

Function Constructor Pattern

MyModule is a reference to a function closure. It is not immediately invoked. It still returns an object that contains references to the public API of the module. We can create multiple instances of this function using the new keyword. Each instance maintains its own state (displayName in this case).

var MyModule = function(){
    var displayName

    function setName(name){
        displayName = name
    }

    function printName(){
        console.log('Hello ' + displayName)
    }

    return{
        setName : setName,
        printName : printName
    }
}

myModule = new MyModule
yourModule = new MyModule
myModule.setName('Jack')
yourModule.setName('Diane')
myModule.printName()
yourModule.printName()

Hello Jack
Hello Diane

Tuesday, October 17, 2017

JavaScript ES6 ES2015 New Feature Overview

JavaScript adds more useful language features in ES6 (ES2015).

New features can be used right now while being backwards compatible with older browsers by using Babel js which transpiles ES6 to ES5. Babel js can be used in a build step for a js project.
https://babeljs.io/

ES6 be used on the backend (nodeJs) and front end (React, etc.).

Destructuring

Take an object or an array and rip it apart into variables.

// object
var o = {
    p1: 1,
    p2: 2
}
var {p1, p2} = o
console.log (p1, p2)

1 2

// array
var a = [1, 2]
var [v1, v2] = a
console.log (v1, v2)

1 2

// function arguments
var o = {
    arg1: 1,
    arg2: 2
}

var fn = ({arg2, arg3, arg1}) => {
    console.log(arg1, arg2, arg3)
}

fn(o)

1 2 undefined

Spread Operator

function fn(a1, a2, a3){
    console.log(a2)
}

var arr = [1, 2, 3]
fn(...arr)

2

var arr = [1, 2, 3, 4, 5]
var [first, ...theRest] = arr
console.log(first)
console.log(theRest)

1
(4) [2, 3, 4, 5]]

var ar1 = [4, 5]
var ar2 = [1, 2, 3]

var ar = [...ar2, ...ar1, 6]
console.log(ar)

(6) [1, 2, 3, 4, 5, 6]

Template Strings

// use back tick and ${varName}
var name = "Slim Shady"
var formattedStr = `My name is
${name}`

console.log(formattedStr)

My name is
Slim Shady

Block Scoping

// var scoping is at function level
// No matter where a variable is defined in a function,
// the variable is hoisted to the top of the function
// let
// Limits scope of a variable to a block (e.g. if and loop stmt blocks)
// Use let EVERYWHERE instead of var

let v = 1

if (true){
    let v = 2
    console.log(v)
}

console.log(v)

2
1

Constants

// const to define a variable that can be assigned to only once
// However, an object assigned to a const CAN be mutated
// user const everywhere if you prefer immutable objects in JavaScript

const c = 1
c = 2
console.log(c)

Uncaught TypeError: Assignment to constant variable.

Arrow Functions

var fn =(a, b) => {
    return a + b
}
console.log(fn(1, 2))

// implict return
var fn = (a, b) => a + b
console.log(fn(2, 3))

3
5

const total = [0, 1, 2, 3].reduce((sum, value) => sum + value, 1)
console.log(total)

7

// arrow functions automatically set lexical context
// may not be desired when writing callbacks for some libraries,
// such as jQuery where this is bound to jQuery library
var o = {
data: 1,
print : function(){
console.log(this.data)
}
}
 o.print()

1

// must bind to this in order to access the data
var o = {
data: 1,
print : function(){
setTimeout(function() {
console.log(this.data)
}.bind(this), 100)
}
}
o.print()

1

// Alternate: use arrow function, no need to bind this
var o = {
data: 1,
print : function(){
// automatically binds the this context
setTimeout(() => {
console.log(this.data)
}, 100)
}
}
o.print()

1

var numbers = [1,2,3,4,5]
var strings = numbers.map(n => n.toString())
console.log(strings)

(5) ["1", "2", "3", "4", "5"]

// How to use 'this' in a timer function (without arrow functions),
//  whose context is Global context, not the function context
//  this.val is scoped to the function
//  define'that' variable in the function closure to keep a reference to 'this'
//  to be accessed by setTimeout function that runs in global scope
function fn() {
    var that = this
    this.val = 0

    setTimeout(function inc(){
        // can't use this.val because this function is in global scope
        that.val++
    }, 0)

    this.print = function() {
        console.log(that.val)
    }
}

var f = new fn()

setTimeout(() => f.print(), 100)

1

// arrow functions are lexically scoped to the block they are contained
//  now we no longer have to preserve 'this' in 'that' variable
function fn() {
    this.val = 0

    setTimeout(() => {
        this.val++
    }, 0)

    this.print = function() {
        console.log(this.val)
    }
}

var f = new fn()

setTimeout(() => f.print(), 100)

1

Classes

class Base{
    constructor(){
        this.data = 1 
    }
 
    fn(){
        console.log('Base ' + this.data)
    }
}

class Derived extends Base{
constructor(){
        super()
    }
    fn(){
        console.log('Derived ' + this.data)
    }
}

var base = new Base()
base.fn()

var derived = new Derived()
derived.fn()

Base 1
Derived 1

Module System

Replaces 'require' library

Export (module1.js):
module.exports.pi = () => 3.142
module.exports.multidentity = () => 1

// entire module export is replaced with this function
export default function(){
}
// export entire module
export default {
}

To export function:
export function fn(){
}

To export variable:
export const pi = 22/7

To import:
import module1 from "module1"

To import (with destructuring, selectively pull what you need):
import {pi, multidentity} from "module1"

To import with an alias:
import {pi, multidentity as one} from "module1"
console.log(one)

Async (Generator function) Function

async function() {
var data = await $.get(url)
console.log(data)
}

Friday, October 13, 2017

Immutable data in JavaScript


Immutable Data

How not to change existing structure data itself but make a new copy of the data to work with

Object 

var a = {p1 : 'A', p2 : 3.142}
// {p1: "A", p2: 3.142}

// Make a copy of object referenced by a
// and replace the value of property p1 with the one specified (i.e. 'B')
var b = Object.assign({}, a, {p1 : 'B'})
// {p1: "B", p2: 3.142}

// same as above, but using the Object Spread Operator
var c = {...a, p1 : 'C'}
//{p1: "C", p2: 3.142}

Arrays

concat, filter, map, and reduce return new arrays.

var a = [1,2,3]
// [1, 2, 3]

// create a new array from contents of a and add another element to it (i.e. 4)
var b = a.concat(4)
// [1, 2, 3, 4]

Objects with Arrays

Objects that have arrays embedded in them.

var a = {p1 : "myList", ar : [1,2,3]}
// {p1: "myList", ar: Array(3)}
// ar : (3) [1, 2, 3]

var b = Object.assign({}, a)
// {p1: "myList", ar: Array(3)}
// ar : (3) [1, 2, 3]

// make a copy of array from object a into object b
// so that changes to either arrays do not effect eachother
b.ar = a.ar.concat(4)
// ar : (4) [1, 2, 3, 4]

Tuesday, October 3, 2017

React JS Q&A

1. What is it?

JavaScript library for building HTML user interfaces for the Web Browser.
React abstracts away the generation of HTML as JSX (a representation of HTML in JavaScript).

2. How does it work?

  • Uses JavaScript to product HTML.
  • Uses JSX, a special syntax to specify HTML tags with in JavaScript. JSX is transpiled to regular JavaScript that runs in any browser (createElement() etc.).
  • React creates a virtual DOM in memory that is rendered as the DOM of the Web Browser.

3. How is React code organized?

  • React code is organized as Components.
  • A React Component is either a Function Component or a Class Component.
  • Function Component is does not have an internal state.
  • Class Component can maintain an internal state.
  • React application is created by composing React Components.
  • React Components are usually rendered on the client although they can rendered on the Server using node.js.

4. What is a React Function Component?

  • Receives props
  • Returns JSX
  • JSX is converted to HMTL by transpiler
const Button = (props) => {
return (
  <div>
      <span>Action: </span>
      <button>{props.label}</button>
    </div>
  );
};

ReactDOM.render(<Button label='Go'/>, mountNode);

5. What is a React Class Component?

  • Class Component receives props just like Function Component but as as data member of the class
  • this.state is a special data member of the class that holds state of the component
  • render() is a special function that returns the JSX

class UCaseComponent extends React.Component {
  state = {enteredValue : 'initial', uppercaseValue : 'initial'.toUpperCase()};
  
  handleTextChange = (e) =>{ 
    this.setState({enteredValue: e.target.value, uppercaseValue :  e.target.value.toUpperCase()});
}
  
  render() {
    return (
    <div>
      <input type="text" value={this.state.enteredValue} onChange={this.handleTextChange}/>
      <div><span>{this.props.labelEnteredValue}: </span>{this.state.enteredValue}</div>
      <div><span>{this.props.labelUppercase}: </span>{this.state.uppercaseValue}</div>
    </div>
   )
  }
}

ReactDOM.render(<UCaseComponent labelEnteredValue='Entered' labelUppercase='Uppercase'/>, mountNode);

6. How does React components pass data?

  • React passes data as properties among components (props).
  • Properties are immutable.

7. How does React maintain state?

  • this.state member (data object) of a React component keeps state around for a component.
  • this.state member of the top-level component maintains state for the application.
  • Change is state automatically triggers a re-render of affected DOM elements. React performs a tree reconciliation of the Virtual DOM with the Browser DOM.
  • To maintain complicated application state, helper state management framework such as Flux can be used along with React.

8. How does React handle HTML events?

  • React encapsulates standard handlers (such as onClick) as function handlers 

9. How can I play with React?

Friday, September 29, 2017

How to guarantee the order of execution in JavaScript?

Use setTimeout() to ensure code is executed in the desired order.


for(i=0; i<100; i++){
setTimeout(function() { console.log(1); }, 0); 
setTimeout(function() { console.log(2); }, 0); 
setTimeout(function() { console.log(3); }, 0);
setTimeout(function() { console.log('-----'); }, 0);
}


1
2
3
-----
1
2
3
-----
1
2
3
-----
1
2
3
-----
.........
.........


for(i=0; i<100; i++){
 setTimeout(function() {
    console.log(1);
    setTimeout(function() {
        console.log(2)
        setTimeout(function() {
            console.log(3)
            }, 0)
        }, 0) 
 }, 0) 
}

100  1
100  2
100  3

Friday, June 16, 2017

Iteration vs. Recursion

Code

def factorial_iter(n):
    num = 1
    while n >= 1:
        num = num * n
        n = n - 1
    return num
   
def factorial_recur(n):
    if n == 1:
        # base case that stops recursion
        print ('  return 1 (this is the top of the stack)')
        return 1
    else:
        print ('  return ' + str(n) + '*' + 'factorial_recur(' + str(n-1) + ')')
        # the function is calling ITSELF
        return n * factorial_recur(n-1)
       
number = 5

print ('-' * 20)
print ('Using Iteration. Factorial of ' + str(number))
print ('-' * 20)
print (str(factorial_iter(number)))

print (' ' * 20)

print ('-' * 20)
print ('Using Recursion. Factorial of ' + str(number))
print ('-' * 20)
print ("factorial_recur: stack trace")
print ("Note how the function calls itself. This is no different than calling another function")
print ("It is called RECURSION because the function is calling ITSELF")
print ("When it reaches the BASE CASE (n==1), it stops calling itself")
print ("The function MUST stop calling itself at some point, otherwise it will never end (likely run of out memory)")
print ("The innermost function call is evaluated first, where n=1 and then return 2 * 1, then return 3 * 2, and so on")
print ("This is called unwinding of the stack. Start from the BOTTOM and evaluate upwards. Think of a function evaluation as follows.")
print ("(5 * (4 * (3 * 2) * (1)))")
print ("Stack trace")
print (str(factorial_recur(number)))

Output

--------------------
Using Iteration. Factorial of 5
--------------------
120
                   
--------------------
Using Recursion. Factorial of 5
--------------------
factorial_recur: stack trace
Note how the function calls itself. This is no different than calling another function
It is called RECURSION because the function is calling ITSELF
When it reaches the BASE CASE (n==1), it stops calling itself
The function MUST stop calling itself at some point, otherwise it will never end (likely run of out memory)
The innermost function call is evaluated first, where n=1 and then return 2 * 1, then return 3 * 2, and so on
This is called unwinding of the stack. Start from the BOTTOM and evaluate upwards. Think of a function evaluation as follows.
(5 * (4 * (3 * 2) * (1)))
Stack trace
  return 5*factorial_recur(4)
  return 4*factorial_recur(3)
  return 3*factorial_recur(2)
  return 2*factorial_recur(1)
  return 1 (this is the top of the stack)
120

Thursday, June 15, 2017

Why use async/await pattern?

While code execution is waiting for an IO bound operation, such as SQL or HTTP operation, to complete, the thread that is waiting can be used by other code operations. Basically, mark the method as async and await the results of an IO bound operation. While waiting, the awaited thread can be utilized for other operations.