Tuesday, December 20, 2016

JavaScript Evolution ECMAScript 6 - Simplified Object

Removing Repetition Object

Here is the typical way we write a return object function.
function buildUser(first, last) {
  let fullname = first + " " + last;
  return {first : first, last : last, fullname : fullname};
}
The returned object with keys and variables with the same name is repetitive. We can remove duplicate variables names from object properties when those properties have the same name as the variables being assigned to them.
function buildUser(first, last) {
  let fullname = first + " " + last;
  return {first, last, fullname};
}
This simplicity called Object Initializer Shorthand.

Object Initializer Shorthand can works anywhere, as long as a new object is returned, not just from function.
let first = "Sam";
let last = "Wong";
let userOld = {first : first, last : last};
let userNew = {first, last}; // Simplified

Object Destructing 

Let's look at another side of reading properties from an object.

Here is the typical way we read properties from an object.
let user = buildUser("Sam", "Wong");
let first = user.first;
let last = user.last;
let fullname = user.fullname;
In ES2015, we can read an object's properties using simplified syntax.
let {first, last, fullname} = buildUser("Sam", "Wong");
console.log(first);
console.log(last);
console.log(fullname);
We can read as well as subset return function properties. Below example, we just want to grab the fullname and leave first, last out.
let {fullname} =  buildUser("Sam", "Wong");;
console.log(fullname);

Method Initializer Shorthand

Here is the typical way we write method in function object.
function buildUser(first, last, age) {
  let fullname = first + " " + last;
  const AGE_LIMIT = 18;
  return {
    first,
    last,
    fullname,
    isAgeOverLimit : function () {
      return age >= AGE_LIMIT;
    }
  }
}
With method initializer shorthand, we can simplify by removing the function ().
function buildUser(first, last, age) {
  let fullname = first + " " + last;
  const AGE_LIMIT = 18;
  return {
    first,
    last,
    fullname,
    // Less character and easier to read.
    isAgeOverLimit () {
      return age >= AGE_LIMIT;
    }
  }
}

Monday, December 5, 2016

JavaScript Evolution ECMAScript 6 - Function with Rest Parameter

JavaScript functions have a built-in object called the argument object. The argument object contains an array of the argument used when the function is called. This kind of function called variadic function.
x = displayTags("A","B","C");
function displayTags() {
  for (let i in arguments){
    let tag = arguments[i];
    addTagTopic(tag);
  }
}
The variadic function gives a major problem where we add an argument, its break our code.
x = displayTags("A","B","C");
function displayTags(targetElement) {   let target = findElement(targetElement);   for (let i in arguments){     let tag = arguments[i]; // Break since the last argument it is no longer a tag.     addTagTopic(tag);   } }
The new rest parameter syntax allows us to represent an indefinite number of arguments as an Array. This way, changes to function signature are less likely to break the code.
function displayTags(...tags) {
  for (let i in tags){
    let tag = tags[i];
    addTagTopic(tag);
  }
}
// Rest parameter must go last.
function displayTags(targetElement, ...tags) {
  let target = findElement(targetElement);
  for (let i in tags){
    let tag = tags[i];
    addTagTopic(tag);
  }
}

JavaScript Evolution ECMAScript 6 - Function with Default Parameter

In ES2015, a developer can add a default parameter into a function. Example:
function loadProfile(usernames=[]){
  if (usernames.lenght > 3){
    let loadingMessage ="This will take a while.";
  }
}
With default parameter, you can call the function either
loadProfile(['Simon','Alex','Arlene']);
Or
loadProfile();
Scala has more powerful default parameter. Let's create Scala function with default parameter.
def addInt(a:Int=5, b:Int=7) = {
  var sum: Int = a + b;
  return sum
}
You can call the function by passing the parameter using a pointer.
addInt(b=10)
Passing parameter using pointer is not implement in JavaScript.

JavaScript Evolution ECMAScript 6 - Using let and const

Prior executing code, JavaScript moves var declarations all the way up to the top of the scope. This is known as a hoist. Example:
function loadProfile(usernames) {
  if(usernames.lenght > 3) {
    var loadingMessage = "This will take a while";
  }
}
JavaScript runtime transform to
function loadProfile(usernames) {
  var loadingMessage;
  if(usernames.lenght > 3) {
    loadingMessage = "This will take a while";
  }
}
This explained developer can access the variable outside the block. Example:
function loadProfile(usernames){
  if(usernames.length > 3) {
    var loadingMessage = "This will take a while";
  }
  consolo.log (loadingMessage );
  // Output is unexpected - can be "This will take a while" or undefined.
}
var variable can be accessed in entitled function which might cause unexpected behaviour. One way you can avoid this by introducing a new variable declaration let.

let variables are scoped to the nested block and are Not hoisted. Block is any code section within curly braces like if, else, while, etc. Example:
function loadProfile(usernames) {
  if (usernames.length > 3) {
    let loadingMessage ="This might take a while";
  }
  consolo.log(loadingMessage);
  // Output is ReferencesError: loadingMessage is not defined.
}
Variables declared with let can be reassigned, but cannot be redeclared within the same scope.
let loadingMessage = "Hello";
loadingMessage = "Goodbye"; // Reassigning is allowed.
let loadingMessage = "Hello";
let loadingMessage = "Goodbye";
// Re declaring is not allowed.
// TypeError: Identified 'loadingMessage' has already been declared.
Second type of new variable is const. const keyword created read-only named constant. Example
const MAX_USERS = 3;
Constant cannot be reassigned. Example:
const MAX_USERS = 3;
MAX_USERS = 10; // Error
Constant must be assigned an initial value. Example:
const MAX_USERS = 3; // No error.
const MAX_USERS;
MAX_USERS = 3; // Error
Constant are scoped to the nearest block, same to let.

Monday, November 28, 2016

Angular 2 Part 5.3 - HTTP

In part 5.3, we are going to fetch our data using HTTP JSON call instead of mock data.

There are 5 steps to make it happen:

1. Create a JSON data file to simulate the data from the server - car-parts.json.
{
 "data" : [
  {
   "id":1,
   "name":"Super Tires",
   "price":2.0,
   "description":"These tires are the very best",
   "inStock":5,
   "image":"/images/example1.png",
   "featured":false,
   "quantity":0
  },
  {
   "id":2,
   "name":"Reinforced shocks",
   "price":4.99,
   "description":"Shock made from krytonite",
   "inStock":4,
   "image":"/images/example2.png",
   "featured":true,
   "quantity":0
  },
  {
   "id":3,
   "name":"Padded Seats",
   "price":2,
   "description":"Super soft scats for a smooth ride.",
   "inStock":0,
   "image":"/images/example3.png",
   "featured":false,
   "quantity":0
  }
 ]
}

2. We need to include HTTP and RxJS Libraries. The HTTP library provides the get call we will use to call across the internet. The RxJS library stands for Reactive Extensions and provides some advance tooling for our HTTP Calls. If you used the 5 minutes QuickStart, you have already included these libraries using systemjs.config.js.

3. Import HTTPModule in main.ts. We can skip adding HTTP as provider because it had already added in HTTPModule.
import {NgModule, Component} from '@angular/core';
import {AppComponent} from './app.component';
import {CarPartComponent} from './car-parts.component';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import { RacingDataService } from './racing-data.service';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

@NgModule ({
  imports:      [ BrowserModule, FormsModule, HttpModule ], // List down all component will be used.
  declarations: [ AppComponent, CarPartComponent ], // Import dependencies.
  bootstrap:    [ AppComponent ], // Indicate first component to launch.
  providers:  [ RacingDataService ] // Now all subcomponents can ask for (inject) our RacingDataService.
})

class AppModule {}

// Start the application in web browser.
platformBrowserDynamic().bootstrapModule(AppModule);
4. Now we can inject HTTP and using it in racing-data.service.ts.
import { CARPARTS } from './mocks';
import {CarPart} from './car-part';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class RacingDataService {

 constructor(private http: Http) {}

 getCarParts() {
  return this.http.get('app/car-parts.json')
   .map(response => <CarPart[]>response.json().data);
 }

}
response = data returned.
<CarPart[]> = Tells our TypeScript compiler to treat this like an arrays of CarPart.
response.json() = For each response, parse the string into JSON.
.data = The array we want is under the data keyword.

5. Since our service returns an observable, we need to subscribe to that data stream and tell our component what to do when our data arrives.
import {Component} from '@angular/core';
import {CarPart} from './car-part';
import { RacingDataService } from './racing-data.service';

@Component({
  selector: "car-parts", // Display in selector defined in app.component.ts
  templateUrl: "app/car-parts.component.html",
  styleUrls: ["app/car-parts.component.css"]
})

export class CarPartComponent {
  carParts : CarPart[];

  // Declare a constructor
  constructor (private racingDataService: RacingDataService) {}

  ngOnInit() {
    this.racingDataService.getCarParts()
      .subscribe(carParts => this.carParts = carParts); // When carParts arrive on our data stream, set it equal to our local carParts array.
  }

  totalCarParts(){
    let sum = 0;
      if(Array.isArray(this.carParts)) {
        for (let carPart of this.carParts) {
          sum += carPart.inStock;
        }
      };
    return sum;
  }

  upQuality(carPart){
    if (carPart.quantity < carPart.inStock) carPart.quantity++;
  }
 
  downQuality(carPart){
    if (carPart.quantity != 0) carPart.quantity--;
  }

}

That's all for Angular 2 sample and I hope you all enjoyed. Here are some tools you might interest.

  • Angualr Angury an Angular 2 debugging tool.
  • Angular CLI - Angular Command Line Interface for developer kicks start project really fast.
Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 5.2 - Service using Dependency Injector

In Part 5.1, we introduced the simplest way to create service. However, this is yet a best solution because we need to create new RacingDataService every time when we need to fetch the data. This would used up more memory.

This is where dependency injection come in. When you run Angular 2 application, it creates a dependency injector. An injector is in charge of knowing how to create and send things.

One of the advantages is that dependency injection know how to resend the same service if the injector already created a service.

There are 3 steps to make all work in our example:

1. Add the injectable decorator to racing-data.service.ts.
...
import { Injectable } from '@angular/core';

@injectable()
...

2. Let our injector know about our service by naming it as a provider in main.ts
@NgModule ({
  imports:      [ BrowserModule, FormsModule, HttpModule ], // List down all component will be used.
  declarations: [ AppComponent, CarPartComponent ], // Import dependencies.
  bootstrap:    [ AppComponent ], // Indicate first component to launch.
  providers:  [ RacingDataService ] // Now all subcomponents can ask for (inject) our RacingDataService.
})

3. Inject the dependency into our car-parts.component.ts
export class CarPartComponent {
  carParts : CarPart[];

  // Declare a constructor
  constructor (private racingDataService: RacingDataService) {}

  ngOnInit() {
    this.racingDataService.getCarParts()
  }

  ...
}

Now our application is more scalable because our dependencies aren't strongly tied our classes.

Download Car Part Source:
https://github.com/htsiah/angular2-carparts

Angular 2 Part 5.1 - Service

Service is used to organize and share code across your app, and they's re usually where you create your data access.

In our car part example, we are using mock file for data loading. Actually this is not a very good solution because we need to import mock in every file that need the data. Also, it is not easy to switch between real and mock data. This sort of data loading is best left to service classes.

Let create the simplest service by creating racing-data.services.ts. The flow will be car-parts.component.ts -> racing-data.services.ts -> mock.ts.

Here is our racing-data.services.ts:
import { CARPARTS } from './mocks';

export class RacingDataService {

 getCarParts() {
  return CARPARTS ;
 }
}

Our car-part.component.ts will lookup the new created racing-data.service.ts instead of mock.ts.
...
import { RacingDataService } from './racing-data.service';
...

export class CarPartComponent {
  ...
  ngOnInit() {
   let racingDataService = new RacingDataService();
   this.racingDataService.getCarParts()
  }
  ...
}

Download Car Part Source:
https://github.com/htsiah/angular2-carparts