Sunday, September 16, 2018

Typescript - Static keyword with Property,method,Constructor examples

In this blog post, We are going to learn Static keyword with properties, methods, and constructor of a class in typescript.
Typescript - Static keyword with Property,method,Constructor examples

Static keyword

static is a keyword which can be applied to properties and methods of a class. Static members are accessed using directly using class names.

static properties and Method example

When you want to call any methods in a class, we will use object instance for accessing it methods, Static methods will use class names
In the class,
  • Declared static variable and nonstatic variable
  • Declared static method and nonstatic method
  • static methods and properties are accessed using class names
  • nonstatic methods and variables are accessed using an instance of a class ie object.
It gives compilation error for below cases
  • calling a static method with an object or instance names
  • calling non-static method with class names
class MyClass {
    static staticVariable: number = 0;
    nonStaticVariable: number = 0;
    constructor() {
        console.log("constructor");
    }
    nonStaticMethod() {
        console.log("non static method")
    }
    static staticMethod() {
        console.log("Static method")
    }
}

MyClass.staticMethod(); // This works fine
let myclass1 = new MyClass(); 
myclass1.nonStaticMethod() // This works fine

myclass1.staticMethod() // Compilation Error
MyClass.nonStaticMethod()  // Compilation Error

Static Constructor

 when the static keyword is applied to the constructor, Compiler gives compilation error 'Static modifier cannot appear on a construct declaration'. In a Typescript, static keyword is not applied to a Class constructor.
class ClassDemo {
    msg: string;
    static constructor(msg: string) {
        this.msg = message;
    }
    hello() {
        return "Hello, " + this.msg;
    }
}
let classDemo = new ClassDemo("world");

Example 

We can write a static keyword in different way using static method. Declare static initialization method which will initialize data

class ClassDemo {
    static msg: string;
    constructor() { 
    }
    static construct() {
        this.msg="static typescript example"
        console.log('construct static method')
    }
}
console.log(ClassDemo.construct)

Tuesday, September 11, 2018

Typescript - Object Type and Object with examples

In this blog post, We are going to learn the typescript object type with examples.
Typescript - Object Type and Object with examples

In the typescript, the object has three variations of creating objects.

1. Object
2. object
3. {}

Typescript object type 

Typescript introduced a new data type called object type. this object represents types which are not primitive types like string, number, void, boolean, null and defined.
The reason to introduce to other object type is as follows

Below Javascript Object class has methods which take an object as a parameter. In Typescript, there is non-primitive type representation for this methods. object type is introduced.

Object.getOwnPropertyDescriptor
Object.create
Object.observe
passing primitive values to the above methods throws at runtime. Typescript gives compilation error because of the object type assertion check
object declaration
const obj: object = {};

Object Class 

This is Object class which is core Superclass for all javascript API classes which contain methods toString and toLocalString

Empty Object -{}

This is a custom object which has an empty object with no variables and methods. Empty Object and Object point to the same type
let myobject = {};
myobject.key = 'test';
In the empty object, there is no key associated, It gives compilation error - Property key does not exist on type{} Object also can be created using predefined properties Here created object of Emp with two properties name and id of type string and number Typescript treat this object as {name:string,id: number} when you assign any values other than of different types, It gives compilation error

Examples

var Emp = {
  name: 'Tom',
  id: 1
};

Emp = {
  name: 'Kiran',
  salary: 2000
};
In the below example, Created object, and now changing object with different values as well as modifying object structure, This gives compilation error as a new object is not assignable to an existing object
The object can be used in many ways like below thing

  • The object contains functions including properties 
  • Can be created using object literals 
  • Can be passed an object to a function 
  • Can also object verified using duck typing means if the two objects contain 1. Same type 2. Same properties

How to check if two objects type equality?

Typescript Reflection API provides a constructor to check object type and returns ClassName Here is an example of checking objects of the same type.
class Parent {}
class Child extends Parent {}
var parent = new Parent();
var child = new Child();
var parent1: Parent;
parent1 = new Child();
console.log(parent.constructor == Parent); // returns true 
console.log(child.constructor == Child); // returns true
console.log(parent1.constructor == Child); // returns true
console.log(parent1.constructor == Parent); // returns false

Typescript let, var, Const keyword with examples | Javascript | ES6

let var, Const keywords are used to declared variables in typescript and javascript. Variables can be declared globally or locally.

Var keyword

the var keyword is for a variable declaration of javascript. Typescript behavior also same as the functional scope
  1. Variable declared with this keyword scope is either locally if declared in a function or globally if declared outside 
  2. if the variable is not used var keyword  for declaring a variable, It assumes global variables
  3. the variable is redeclared with var keyword, It will not lose its original value
  4. variable returned undefined without declaring and initialization its value

example and usage

var value = 11;
var value1;
function myfunction() {
    value = 456; //  allowed
    value2 = 14
    console.log(value) // 456
    console.log(value1) // undefined
    console.log(value2) // 14
}
myfunction();

Let Keyword 

 Let keyword introduced ES6 - ES2015, It is used to declare a variable in block scope let keyword with colon defines type annotations
Here is an example of let keyword.
let value = "abc";
console.log(value); // abc
if (true) {
    let value = "newabc";;
    console.log(value); // newabc
}
console.log(value); // abc
Redeclaring same variable with let in the current context throws SyntaxError - Can not redeclare blocked-scope variable value
let value = "abc";
let value = "newabc";

Let variable hosting

when the variable is used without declaring it throws Uncaught ReferenceError: value is not defined
function myfunction() { 
    console.log(value);
}
myfunction()

const keyword 

const keywords same like let and there is the difference. a variable declared with const must be initialized immediately once const variable declared, It values not changed by reassigning new value Example
const value = 123;
function myfunction() {
    value = 123; // not allowed
}

ES6 Let and Const temporal dead zone 

This was introduced in ES6. Calling variable without declaring it using let and const has thrown ReferenceError. This is to avoid the programming exceptions and safeguard for debugging variables

Difference between Let and var keyword

Both are used to declare a variable Let create a variable in blocked scope var creates a variable in global scope Difference example is as below
// example var
for (var val = 0; val < 2; val++){
   console.log(val) 
}
console.log(val) // 5

// example let
for (let val = 0; val < 2; val++){
   console.log(val)
}
console.log(val)// undefined

Monday, September 10, 2018

Typescript Array Sort method with example | javascript

This blog post, We are going to learn how to Sort Array in javascript or typescript

Array Sort method

This method sorts the elements of an array in ascending or descending.
Elements are simple strings, Object which contains key and values or Typescript classes.

Syntax

Array.sort(ComparatorFunction)
Parameters are ComparatorFunction is a function which specifies the order of the elements, If not passed, Default sorting is applied.

Array String sort Example

Array Declared and initialized with new Array() and strings separated in comma No comparator function passed and Array.sort() method is used
var arrayStrings = new Array("one", "two", "there", "four"); 
var sortedArray = arrayStrings.sort(); 
console.log(""+sortedArray );
Output is
four,one,there,two

Object Array Sort Example ascending 

The object can be directly created using an array or you can create an Interface. This Emp object contains id and names This example sort the objects by name property First created Emp interface.
 interface Emp {
     id: number;
     name: string;
}
Next, Create Array of Objects and initialize with values
var emps: Emp[] = [
    { id: "5", name: "Kiran" },
    { id: "1", name: "Frank" },
    { id: "2", name: "Tom" },
    { id: "51", name: "Abc" }
]
And Write a Compare Function for Name of Emp object
var compareName = function (emp1: Emp, emp2: Emp) {
        if (emp1.name > emp2.name) { return -1; }
        if (emp1.name < emp2.name) {return 1; }
        return 0;
    }
 
Finally Call Array.sort() with compare function
var sortedArray = emps.sort(compareName); 
console.log(sortedArray );
Output is
0: {id: "2", name: "Tom"}
1: {id: "5", name: "Kiran"}
2: {id: "1", name: "Frank"}
3: {id: "51", name: "Abc"}

Sort Array Object Data by Date property Example

The object contains key date property. We can sort the object data based on date ascending or descending. Need to supply comparator custom code which handles Date comparisons. First Date string is converted to an Inbuilt Date object.
Date ascending 
This is an example sort array of object date by date ascending
interface Emp {
     id: number;
     name: string;
     date: Date;
}
var emps: Emp[] = [
    { id: "5", name: "Kiran",date:"2018-05-05" },
    { id: "1", name: "Frank",date:"2017-05-05"},
    { id: "2", name: "Tom",date:"2016-05-05" },
    { id: "51", name: "Abc" ,date:"2018-10-05"}
]

var compareDate = function (emp1: Emp, emp2: Emp) {
    var emp1Date = new Date(emp1.date).getTime();
    var emp2Date = new Date(emp2.date).getTime();
    return emp1Date > emp2Date ? 1 : -1;  
}
var sortedArray = emps.sort(compareDate); 
console.log(sortedArray );
Output is

0: {id: "2", name: "Tom", date: "2016-05-05"}
1: {id: "1", name: "Frank", date: "2017-05-05"}
2: {id: "5", name: "Kiran", date: "2018-05-05"}
3: {id: "51", name: "Abc", date: "2018-10-05"}
We will see the Sort Date by descending.
Date descending
var compareDate = function (emp1: Emp, emp2: Emp) {
    var emp1Date = new Date(emp1.date).getTime();
    var emp2Date = new Date(emp2.date).getTime();
    return emp1Date > emp2Date ? -1 : 1;  
}
Output is
0: {id: "51", name: "Abc", date: "2018-10-05"}
1: {id: "5", name: "Kiran", date: "2018-05-05"}
2: {id: "1", name: "Frank", date: "2017-05-05"}
3: {id: "2", name: "Tom", date: "2016-05-05"}

Underscore Array Sort Example

UnderscoreJS is a javascript library which provides a lot of utility functions. It provides sortBy function which accepts an array and a function as an argument. This library can be used in javascript or typescript applications using npm package manager installation and configuring module Here is an example of array string sorting in descending
var sortedArray=_.sortBy(["four", "one", "zero"], function (value) { return value.toLowerCase(); });
console.log(sortedArray);
output is
["four","one","zero"]

Typescript - Beginner Guide to Switch case tutorial with examples

In this blog post, we are going to learn Switch case statement with examples

Switch case Introduction
Typescript Switch case tutorial

switch case is a kind of conditional expression which checks and evaluates the expression and matched case block of code executes. This is used in place of if and else conditional expressions. It will avoid multiple if and else statements to simplify the code 

Syntax

switch(conditionalexpression)
{
case value_expression:
// body statements
break;
case value_expression1:
// body statements
break;
default:
// body statements
break;
}
conditionalexpression
conditional Expression is evaluated and matching code block is finding out using case and default 
Case Block - This code is executed when Conditional Expression is matched with case block 
Default Block - This code is executed when Conditional Expression is not matched with case block Break keyword is used to break or exit from current case block and it is optional. If it is not used, remaining cases will be executed after executing matched case statement

Example

Here Single case statement is used and the default is used if none of the cases are matched.
var value = 'a';
switch (value) {
  case 'a':
    console.log(' Letter a Checked');
    break;
  case 'b':
    console.log(' Letter b Checked');
    break;
  default:
    console.log(' default letter Checked');
}
Output is
Letter a Checked

Multiple Switch cases statement Example

Multiple cases can be placed for a single code of block. Here is an example of this
var value = 'c';
switch (value) {
    case 'a':
        console.log(' Letter a Checked');
        break;
  case 'b':
  case 'c':
  case 'd':
        console.log(' Letter b,c and d Checked');
    break;
  default:
        console.log(' default letter Checked');
    break;
}
Output is
Letter b,c and d Checked

Switch Case Enum example

In switch expression, Used Enum constants. and also provided multiple case statements with enum constants
enum Day {
  MONDAY,
  TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
  SUNDAY
}
case Day.SATURDAY:
function isWorkingDay(day: Day) { switch (day) { case Day.SUNDAY: console.log('holiday'); break; default: console.log('working day'); break; } } const tuesday = Day.TUESDAY; const sunday = Day.SUNDAY; isWorkingDay(tuesday); // working day isWorkingDay(sunday); // holiday
Output is
working day
holiday

Typescript Configuration - noFallthroughCasesInSwitch 

noFallthroughCasesInSwitch value is boolean ie true or false. 
This can be configured in tsconfig.json of typescript application.This is used to return an error for fall through switch cases Following is switch case fallthrough example where there are no break statements. if noFallthroughCasesInSwitch=true, The below case is not allowed
switch(value) {
    case 1:
        // statements
    case 2:
// statements 2
}

Sunday, September 9, 2018

Es6 Generator Functions Yield in javascript | Typescript | examples

In this blog post, We are going to learn Generator Functions and Yield Keyword with examples.
First We will see how Normal Function works? Normal Functions are called, executes it and the function returns finally either return the value of function body execution is completed. Function Example here is a function example, When function Method is called, Sequence of statements in a body executed, finally returned value and iteration is stopped its control.
function method(){
//body
return value;
}

method();

Generator Function Introduction 

The generator is a special kind of Functions that introduced in ES6- ES2015. These functions control the how we want to iterate behavior. when The function is called, It can be paused and resumed. Example Here is an example of Generator Functions
function* generateFunctions() { 
    console.log('Generateor Function started');
    yield 'pause';
    console.log('Generateor Function Completed');
}
const gfunctions=generateFunctions();
console.log(gfunctions.next());
console.log(gfunctions.next());
console.log(gfunctions.next());
Output is
[object Generator]
"Generateor Function started"
Object { value: "pause", done: false }
"Generateor Function Completed"
Object { value: undefined, done: true }
Object { value: undefined, done: true }
We will see the difference between Normal Function and Generator Function 

  • This function starts with function* and normal function starts with function 
  • Function execution paused using yield keyword when the below statement executes, the function is not called, It gets the generator function object.
const gfunctions=generateFunctions();
Initially, Function is not called and suspended, You have to call gfunctions.next() to call function body. next() method returns an object which contains value and done keys. Each time when you called next() method, function resumes its execution and return an object which contains and value and done keys
value: It is the output of yield code execution
done:- status of the execution, false means function execution is not completed

Typescript Function Generator 

When you generator function in typescript, It will no work default and gives the following error TS2339: Property 'next' does not exist on type You have to make configuration changes to tsconfig.json file and fix for the above error is
"target": "es6",
"lib": [
    "es6"
]
Typescript Yield keyword
Typescript supports generator functions and behavior works as expected

ES6 Learn Symbol Type in javascript | Typescript Symbol Type

In this blog post, We are going to learn the Primitive Data type Symbol basics with examples.

ES6 Symbol Datatype

The symbol is a primitive data type introduced with ES6 or ECMAScript 2015 in javascript. Typescript also supports this Symbol as a Primitive data type like String, number, and Boolean.
  • The symbol is a special primitive type which represents Unique values or keys of an object.
  • It is used to identify unique objects with Symbol object. 
  • Symbol variables always return new unique value
All the above examples will work in javascript and typescript

Initialize and Creation

Symbol object is created as follows. It creates unique value for every object creation. Empty Symbol is created by Symbol() And also Can supply the key to Symbol Function as seen below example
var symboleObj = Symbol();
console.log(symboleObj) //Symbol()
console.log(typeof symboleObj) //symbol
var symboleObj1 = Symbol('keyhere');
console.log(symboleObj1) //Symbol(keyhere)

Symbols Unique Check 

The object creates always returns new values. Same Symbol with the same key
let symboleObj1= Symbol("s1");
let symboleObj2 = Symbol("s1");
console.log(symboleObj1==symboleObj2) //false

Key as a Symbol in Object

Symbols can be stored in the object as a key. And value can be retrieved as like normal keys. Object.keys and Object.getOwnPropertyNames will not get the Symbol Keys, meaning Keys are not iterable in for...in for..of iteration process. To retrieve symbol keys, Object.getOwnPropertySymbols is be used.
var symboleObj = Symbol();
let myObject = {
    [symboleObj]: "myvalue",
    "key1": "value1"
}
console.log(myObject) //Object Symbol(): "myvalue"

console.log(myObject[symboleObj]) //myvalue
console.log(Object.keys(myObject))  // return [ 'key1' ]
console.log(Object.getOwnPropertyNames(myObject)) // return [ 'key1' ]
console.log(Object.getOwnPropertySymbols(myObject)) // return [ Symbol() ]

How to Convert Symbol to String

 toString() method returns the String version of Symbol Object. Can also convert to String using String(symboleObj). if you use new String(symboleObj) - It throws 'Uncaught TypeError: Cannot convert a Symbol value to a string'


var symboleObj = Symbol();
console.log(String(symboleObj)) //myvalue
console.log(symboleObj.toString()) //myvalue

How to Convert Symbol to Boolean

Pass Symbol object to Boolean Class, always returns true. Can also be used with ! not operator to return false
var symboleObj = Symbol(123);
console.log(new Boolean(symboleObj)) //true
console.log(!symboleObj) //false

Symbol for method

 Each symbol is created will be registered in the global scope. for() method takes input string - a description which searches global scope for Symbols for the given description and returns the Symbol
let test = Symbol.for('test');
console.log(test === test); // true

How to Convert Symbol to Number

For Number, if the same code is used for Number like new Number(symboleObj), it gives compilation Error: Cannot convert a Symbol value to a number

Pre builtin Symbols

Javascript and typescript defined native symbols as part of the language.
Symbol.iterator Example
This returns the iteration for an object which can be used in for loop syntax. Here is an example of String's iteration of an object
interface IIterationString {
  [Symbol.iterator](): IterableIterator;
}

class StringIteration implements IIterationString {
    private strings = ['one', 'two', 'three']; 

    constructor() {}

    *[Symbol.iterator]() {
        for(let ss of this.strings) {
            yield ss;
        }
    }
}

for(let elem of (new StringIteration())) {
    console.log(elem); // returns one two three
}

Friday, September 7, 2018

Javascript - Add and delete objects from begining and end of an Arrays with examples

Arrays Javascript 

 The array is used to store a collection of objects in insertion ordered Array Supports Queue and stack operations, It has methods which we can add an element to start/end of an array. delete an element from start and end of an array

Push() method example

 This method is used to add the element to the end of the array Syntax
push(item0 : Object, [item1 : Object, [...]]) : Number
Here is an example push() method usage
let strs = ["one", "two"];
strs.push("three");
console.log( strs ); // one, two, three

pop() method example 

This removes an element from the end of Array
Here is an example pop() method usage
let strs = ["one", "two","three"];
strs.pop();
console.log( strs ); // one, two

shift() method example 

shift() method removes the elements from the start of the array and returns the first element from the array string
Here is an example shift() method usage
let strs = ["one", "two","three"];
console.log( strs.shift() ); // one
console.log( strs ); // two three

unshift() method example

unshift() method add the object to start of the array and returns the size of the newly modified array
Here is an example unshift() method usage
let strs = ["one", "two","three"];
console.log( strs.unshift('start') ); // 4
console.log( strs ); // start one two three

Es6 Beginner guide to WeakSet class examples in javascript | Typescript WeakSet

WeakSet in ES6

WeakSet is one of the collection class similar to Set class, Other Classes are Set, Map and WeakMap.WeakSet is a Set class which stores collection weak object references,  that is if the reference of the object is null, the object is automatically garbage collected. So WeakSet saves weak references of an object. if the object is referenced/destroyed, Garbage collector automatically removes the object from  WeakSet and memory consumption is less.

Typescript WeakSet

WeakSet class is not defined in the inbuilt class of typescript.
We can use ES6 collection classes in typescript, For this, We need to add some configurations. Please add "lib": ["es6"] of typescript configuration file - that is  tsconfig.json file,  or you can add polyfill.js for this backend support. 

WeakSet Declaration and creation 

Empty WeakSet is created using the new keyword
new WeakSet() 
Can also create a Set object using Iterable object and the iterable object is an array of collections
new WeakSet(iterable : Object)
Here is an example Creating WeakSet from an array of objects
var obj1 = { id: 1 };
var obj2 = { name: 'kiran' };
var weakSet = new WeakSet([[obj1, obj2]]);
console.log(weakSet);

Methods

WeakSet provided methods for adding/removing, check keys, empty set operations. iterable operations are not implemented.

WeakSet.add() method

 It adds a new object to Set  and returns newly modified set
Syntax
add(value : Object) : WeakSet
Example Following is an example of add() method
const weakSet = new WeakSet();
const obj = {id:1};
weakSet.add(obj);
console.log(weakSet);
Output is
[[Entries]]: Array(1)
0:value: {id: 1}

WeakSet.has() method 

has() method returns true if the object already exists in a set, else false
Syntax
has(key : Object) : Boolean
Here is an example usage of WeakSet has() method
const weakSet = new WeakSet();
const obj = {id:1};
console.log(weakSet);
console.log(weakSet.has(obj));// true
console.log(weakSet.has(null));//false

WeakSet.delete() method

This method deletes the object from a set and returns true if exists, else false. Syntax
delete(key : Object) : Boolean
Following is an example for delete() method
const weakSet = new WeakSet();
const obj = { id: 1 };
weakSet.add(obj);
console.log(weakSet.delete(obj));// true
console.log(weakSet.delete(null));//false

Allowed and Not allowed objects in Set

Primitive types - String, Boolean, Number, Undefined and Symbole Objects are not allowed for storing it in Set. Only objects are allowed
var set = new WeakSet();
set.add(new Date())  // Date objects are  acceptable
set.add({ objectkey: 'objectvalue' })// acceptable
set.add(false) // not acceptable, primitive not allowed to store in set
set.add('string') // not acceptable, primitive not allowed to store in set
set.add(123) // not acceptable, primitive not allowed to store in set

Difference between Set and WeakSet

Both used to store a collection of objects
Set WeakSet
Sets stores strong references Objects oof WeakSet are weak referenced/td>
Memory Consumption is high Memory Consumption is less, the objects will be automatically garbage collected if any objects are unreferenced
Objects to store in Set will allow Primitive type like Strings, numbers, Date, Symbols, Functions, Objects, and Dates Objects cannot be Primitive types and Symbol object, Other objects are allowed
Set has iterator implementation methods like keys(),values(), entries() and forEach() methods WeakSet not not implemented iterator, so objects are not iterable

Thursday, September 6, 2018

Es6 Beginner guide to Weakmap class examples in javascript | Typescript WeakMap

WeakMap class in Javascript

Es6 introduced new collection data structure classes. WeakMap is one of the collection class similar to Map class, Other Classes are SetMap and WeakSet Other Classes are Set, Map and WeakSet

WeakMap is a map class which stores key and values and keys stores weak references,  that is if the reference of the key is unreferenced, value for the given key is garbage collected.

So weakMap saves weak references of a key object. if the key object is referenced/destroyed, Garbage collector automatically removes the entry(key and value ) from  WeakMap and memory consumption is less

Typescript WeakMap Example

Typescript has no support for Map or WeakMap, Typescript is an extended version of javascript/ES6, We can use with some configuration. Es6 classes can be used in typescript with configuring Es6 library in typescript configuration. In the tsconfig.json file, add "lib": ["es6"] or you can add polyfill.js for this classes. Typescript has no built-in classes supported for Map, But Typescript supports same data structure that ES6 supports.

WeakMap Declare and Creation

Empty WeakMap is created using the new keyword
new WeakMap() 
Can also create using iterable objects, these objects contain key and values pairs
new WeakMap(iterable : Object)
For example, We will create a Map using an array of key and values
var key = { id: 1 };
var value = { name: 'kiran' };
var map = new WeakMap([[key, value]]);
console.log(map)
Output is
[[Entries]]: Array(1)
0: {Object => Object}
key: {id: 1}
value: {name: "kiran"}
length: 1

Methods. 

WeakMap has only methods for adding/removing, check keys, empty map operations. iterable operations are not implemented.

WeakMap.set() method

It stores key and values in the map Syntax
set(key : Object, value : Object) : WeakMap
Primitive types - String, Boolean, Number, Undefined and Symbole Objects are not allowed for the key value. Only objects are allowed
var weakMap = new WeakMap()
var key = { id: 1 };
weakMap.set(key, 'v')
console.log(weakMap.has(key)) 
console.log(weakMap.has(null)) 
Output is
[[Entries]]: Array(1)
0: {Object => "v"}
key: {id: 1}
value: "v"
length: 1

WeakMap.has() method

has() method returns true if the key already exists, else false
has(key : Object) : Boolean
the parameter is object key
Example
Here is an example of has method usage.
var weakMap = new WeakMap()
var key = { id: 1 };
weakMap.set(key, 'v')
console.log(weakMap.has(key)) //true
console.log(weakMap.has(null))  // false

WeakMap.delete() method

This method is used to remove the key from a map and true if exists, else false.
Syntax
delete(key : Object) : Boolean
Example
here is an example of delete method usage
var weakMap = new WeakMap()
var key = { id: 1 };
weakMap.set(key, 'v')
console.log(weakMap.delete(key))  // true
console.log(weakMap.delete(null))  // false

Allowed and not allowed Keys Example 

keys of WeakMap not allowed primitive types and Symbole object and gives compilation error - Argument of type 'Symbol' is not assignable to a parameter of type 'object'.
var map = new WeakMap()
map.set(new Date(), function currentTime () {})  // acceptable
map.set(() => 'key', { objectkey: 'objectvalue' })// acceptable
map.set(1,123) // not acceptable, primitive not allowed as keys
map.set(Symbol('symbol'), [6, 21]) // not acceptable, Symbole not allowed as keys
console.log(map) 

WeakMap and Map Usage difference example

Following is an example of Map and WeakMap methods usage
var map=new Map();
var weakMap=new WeakMap();
var object1={'one':'two'};
var object2={'five':'six'};
map.set(object1,'kiran')
weakMap.set(object2,'kiran2')
console.log(map.get(object1)) // kiran
console.log(map.get(object2)) // undefined

var map=new Map();
var weakMap=new WeakMap();
var object1={'one':'two'};
var object2={'five':'six'};
map.set(object1,'frank');
weakMap.set(object2,'frank2');
console.log(map.get(object1)); // frank
console.log(weakMap.get(object2)); // frank2

Difference between Map and WeakMap

Both used to store key and values only
Map WeakMap
Map Keys are strong references Keys of WeakMap are weak referenced/td>
Memory Consumption is high Memory Consumption is less, the entry will be automatically garbage collected if any keys are unreferenced
Keys can be a Primitive type like Strings, numbers, Date, Symbols, Functions, Objects, and Dates Keys cannot be Primitive types and Symbol object, Other objects are allowed
Map has iterator implementation methods like keys(),values(), entries() and forEach() methods Weakmap not not implemented iterator, so keys and values are not iterable

Java8- Learn LocalDateTime Basics with Example

java.time.LocalDateTime

Java8- Learn LocalDateTime Basics with Example

LocalDateTime is introduced in java8 language as part of Date and Time API enhancement. It represents Date and time without timezone information in 2018-09-06T06:12:40 It is immutable object once created, will not be modified It is used to store dates like birthday and holidays with time information. Local Date contains only year, month, Day, hour, minute, second with nano-precision.

Syntax and Signature 

This class implements ChronoLocalDateTime of LocalDate
public final class LocalDateTime
        implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable 

Examples 

We will see how we can use LocalDateTime with usage examples

How to get Current Date and Time

now() method return the date and time using default system timezone.
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println(currentDateTime); //2018-09-06T21:52:49.714773400
It has a static of() method which takes java.time.LocalDate and java.time.LocalTime to create LocalDateTime object. Here is an example of a method usage.
LocalDateTime currentDateTime  = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println(currentDateTime);

Convert String Date to LocalDateTime 

The localdatetime .parse method which accepts string object and DateTimeFormatter instance. The datetimeformatter object created with pattern
String string = "2018-12-12 12:30";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime localDateTime = LocalDateTime.parse(string, dateTimeFormatter);
System.out.println(localDateTime); //2018-12-12T12:30

How to Convert LocalDateTime to java.util.Date 

The date is legacy Date class and LocalDateTime introduced in java8 version.
LocalDateTime localDateTime =LocalDateTime.now();
Date date = java.sql.Timestamp.valueOf( localDateTime );
System.out.println(date);

Convert LocalDateTime to Instant 

It provides ofInstant() method which takes instant object and zone id- system default zone id LocalDateTime.toInstant() method is used to Convert LocalDateTime to Instant.
Instant instant = Instant.now();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
System.out.println(localDateTime);

How to Create LocalDatetime from Epcoh milliseconds?

System.currentTimeMillis() returns current Epcoh milliseconds. Create Instant using Instant.ofEpochMilli() method, convert Instant to LocalDate time
LocalDateTime localDateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), TimeZone
.getDefault().toZoneId());  
System.out.println(localDateTime);

Typescript - Singleton pattern Implementation with example

In this blog post, We are going to learn the Singleton pattern in typescript with examples.

Singleton Design pattern 

Singleton is one of the simple and frequently used design patterns in application development. This pattern enables to create a single instance or object of a class in the application. Only Once an instance of the class is created in an application.
Every programming language provides an implementation for this pattern.
We can also implement the singleton pattern in Typescript. This is a simple creation pattern.

Use cases and advantages 

  1. Providing global access for object creation of a class, It always has one instance is maintained.
  2. In applications, If you are implementing application caching, You will maintain an only single instance of a cache object always.
  3. Maintain single instance when you are dealing with the global configuration in the application

Singleton Pattern implementation

  1. Private modifier for the constructor, So that This class cannot be created by other classes.
  2. A private Static variable that always returns the instance of the same class 
  3. A public static function that returns the instance of the class

Example


class SingletonClass {
    private static instance: SingletonClass;
    private constructor() {
    }
    static getInstance() {
        if (!SingletonClass.instance) {
            SingletonClass.instance = new SingletonClass();
        }
        return SingletonClass.instance;
    }
}

let instance1 = new SingletonClass() // This gives compilation error

let instance2 = SingletonClass.getInstance() 
let instance3 = SingletonClass.getInstance() 

console.log(instance2==instance3) // true
If you create an object using the new operator, it gives compilation error - constructor of class 'SingletonClass' is private only accessible within class declaration Created Instance static member variables, which can be accessed using class instead of Object instances added private modifier to Constructor, Outside classes can not be created using the new operator. Declared static method or a function, which checks if the instance is null or undefined, it creates an instance and returns it, if already exist, just returned the instance

Javascript Learn Infinity Property Basics

Infinity Property

Infinity is a property of a Global Object, that specifies positive values of a numeric data. The default value of infinity is Number.POSITIVE_INFINITY.
 It represents Mathematical Infinity value. In mathematical calculations, Any value is divided by Zero is returned infinity

Syntax

Infinity

Example Usage

The number value is divided by Zero. and Infinity value is always the largest value of any numeric value When you are adding/multiply any value with infinity will get Infinity
console.log(123/0) // Infinity
console.log(Infinity) // Infinity
console.log(Infinity - Infinity) // NaN
console.log(Infinity+Infinity) // Infinity
console.log(Infinity*Infinity) // Infinity
Infinity value is represented in Positive and Negative Number.POSITIVE_INFINITY - Represents Positive infinite values - Infinity Number.NEGATIVE_INFINITY - Represents Negative Infinite value - -Infinity Infinity property usages
  1. This will be used to check arithmetic operations result in comparison with Infinity.
  2. This will also be used to store the infinite value of any calculations
  3. Checking infinite value for Division

Check and Compare Infinity value 

Infinity can be used like a variable in conditional if the expression
var value = 45;
if (45
output is
Value is less than infinite value

Number isFinite() method

isFinite() is defined in Number Object. isFinite() method checks value for a finite number, return true for a finite number, false for infinite number Syntax
Number.isFinite(numericvalule)
Example Following is an example of isFinite() method of usage.
console.log(Number.isFinite(123)) // true
console.log(Number.isFinite(Infinity)) //false
console.log(Number.isFinite(null)) //false
console.log(Number.isFinite(NaN)) //false
console.log(Number.isFinite(-Infinity)) //false
console.log(Number.isFinite(undefined)) //false