Thursday, December 6, 2018

Class not found when running test case during gradle build

Problem:

I got the exception when I run the test case, which is using the generated WSDL source file, and got "Class not found exception" . Because my test case not able to find the genearted source code from WSDL.


Solution:

I added the below line gradle and its working fine.

sourceSets.test.java.srcDirs = ['.apt_generated/xxx,'src/test/java']



Monday, July 16, 2018

BeanExpressionContext' - maybe not public or not valid?

Property or field 'xxxxxxxxx' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?

The solution is just you should read value like below.

@Value("${your.prop.name}")
private List<String> userIdList;

I just removed # symbol from there and its working fine as expected.

Friday, May 11, 2018

Setter and Getter compatability

The below is another way of setting and getting property values and its really a very compatible mode.

Simple Example :


1
2
3
4
5
6
7
8
function User(name, age) {
  this.name = name;
  this.age = age;
}

let john = new User("Test", 25);

alert( john.age ); // 25

Explanation:

1. Line no 6 we are creating value for name and age property.  So the name and age will be assigned  (setter).

2. In line no 8, we are getting age value.

Getter and Setter with Javascript Property

Below is the code how JS code getter and setter should be,


1
2
3
4
5
6
7
8
9
let obj = {
  get propName() {
    // getter, the code executed on getting obj.propName
  },

  set propName(value) {
    // setter, the code executed on setting obj.propName = value
  }
};

Line no 2 and 6 get and set is keyword and propName is your property name to set and get value.

Example:


1
 2
 3
 4
 5
 6
 7
 8
 9
10
let user = {
  name: "FirstName",
  surname: "LastName",

  get fullName() {
    return `${this.name} ${this.surname}`;
  }
};

alert(user.fullName); // FirstName LastName

Explanation:

1. line no 1 user is an object which have name and surname property.

2. Through line no 10, when you call alert(user.fullName) control will be moved to line no 5 and it will be executed.

3. So line no 6 will return the result your user object property with the help of "this".

Example II:


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
let user = {
  name: "First",
  surname: "Second",

  get fullName() {
    return `${this.name} ${this.surname}`;
  },

  set fullName(value) {
    [this.name, this.surname] = value.split(" ");
  }
};

// set fullName is executed with the given value.
user.fullName = "Third Fourth";

alert(user.name); //Third
alert(user.surname);// Fourth





Solution for losing this - Function binding

Top avoid losing of this , we can wrapping a function.

Example :

Solution I:
1
 2
 3
 4
 5
 6
 7
 8
 9
10
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

setTimeout(function() {
  user.sayHi(); // Hello, TestName
}, 3000);

Now above code will work, since we have passed user.sayHi() as function (Outer lexical environment). So it will work like normal method call.

However, using arrow function (ES6) will short your code and solve this problem very easily without any confusing.

Example II: Arrow function :

Solution II:

1
2
3
4
5
6
7
8
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

setTimeout(() => user.sayHi(), 3000);


Example III:

Solution III:
Using bind built in method

Before proceeding we must know its syntax.

let boundFunc = func.bind(context);


Below is the example code and its explanation is below. Now you can understand better.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
let user = {
  firstName: "TestName"
};

function func() {
  alert(this.firstName);
}

let funcUser = func.bind(user);
funcUser(); // TestName

From the above example, func method bind was done and assigned to funcUser. So calling the funcUser will provide the correct result. Means, this bind with user object.

Example IV:

Binding with Object method:



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}`);
  }
};

let sayHi = user.sayHi.bind(user); // (*)

sayHi(); // Hello, TestName

setTimeout(sayHi, 1000); // Hello, TestName






Losing this - Function binding


Actually, this is an old concept only because If you are using ES6 and you don not worry about this. To know more about function binding , check below.

Example Scenario :

Just assume that, you are using setTimeout with object methods or you are trying to passing object methods, then you will loss "this" power.

Means, using this.xxxxx something will give you the result as undefined.

Example code for losing "this":


1
2
3
4
5
6
7
8
let user = {
  firstName: "TestName",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

setTimeout(user.sayHi, 3000); // Hello, undefined!

Explanation:

1. We have set 3 seconds for setTimeout function at line no 8.

2. Now sayHi method will be executed and it try to print firstName with the help of this.firstName.

3. As "this" was lost , it will print undefined.






Wednesday, May 9, 2018

Difference between Call and Apply


1. The call method always expect comma separated parameters.

2. The apply method always expect array of arguments.

3. However, call and apply both expecting object as first parameter.

Note:

In ES6, we know spread operator ... and you can pass an array (or any iterable) as a list of arguments.

So using this spread with call, almost you are achieving apply concept.


1
2
3
4
let args = [1, 2, 3];

func.call(context, ...args); // pass an array as list with spread operator
func.apply(context, args);

From the above code you can find some minor difference, let see what is that

1. The spread operator ... is iterable args.

2. The apply accepts only array-like args.

So an iterate is possible with call and it works.  Whereas we expect an array-like, apply works.

Generally apply will be faster because of its single operation.

func.apply

Already we saw about call and its expecting comma separated parameters. But in apply we should pass array arguments.

A simple example,


1
2
3
4
5
6
7
8
9
function say(time, phrase) {
  alert(`[${time}] ${this.name}: ${phrase}`);
}

let user = { name: "John" };

let arrayData = ['10:00', 'Hello'];

say.apply(user, arrayData); 

Explanation :

1. We are using apply at line no 9. Here user is our context and arrayData is array arguments for this apply.

2. In the arrayData 10:00 will be considered as time and phrase will be considered as Hello.

3. After executing lie no 9 control moves to line 1 to execute a method say and will print the output.


func.call

Its a built-in function method func.call(context, …args) that allows to call a function explicitly by setting this.

The syntax is


func.call(context, arg1, arg2, ...)

A simple example is below,


1
2
3
4
5
6
7
function say(phrase) {
  alert(this.name + ': ' + phrase);
}

let user = { name: "JavaScript" };

say.call( user, "Hello" ); // Javascript: Hello

Explanation :

1. In line no 7, we have used user as our context and Hello as our argument.

2. You can pass multiple parameters like arg1, arg2 etc.,

3. After executing line no 7, control will move to line no 1 and say method will be executed.


Things to Remember :

Generally, most of the people will get ambiguous for call and apply. To remember this, use mnemonic is "A for array(apply) and C for comma (call).







Monday, April 30, 2018

setInterval

It runs the function regularly after the given interval of time. Suppose, If you want to stop the actions you should call clearInterval(timerId).

The setInterval method syntax is same as setTimeout.

Syntax:


let timerId = setInterval(func|code, delay[, arg1, arg2...])

Example:



let timerId = setInterval(() => alert('I will run every 3 seconds continuously'), 3000);

The above alert will show up every 3 seconds once.

setInterval with clearInterval

Example:

1
2
3
4
let timerId = setInterval(() => alert('Test'), 2000);

// after 5 seconds stop the interval
setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000);

Explanation:
       
                1. Line number 1 will be run continuously for every 2 seconds.

                2. But line number 5 will clear the interval time after 5 seconds. So after 5 seconds alert 
                    "Test" will not shown.





setTimeout with clearTimeout

We can use “timer identifier” which will be returned by setTimeout and the same we can use to cancel the execution.

Syntax:



let timerId = setTimeout(...);
clearTimeout(timerId);

Example:



1
2
3
let myVar = setTimeout(function(){ alert("Hello"); }, 3000);

let xxx = clearTimeout(myVar);

Explanation:

1. Line number 1 will be executed initially

2. To display the alert Hello message 3 seconds need to be waited.

3. But line number 3 will be executed before three seconds. So alert message will not be displayed here.

setTimeout


For executing some methods based on some times, then we should go ahead with setTimeout and  setInterval.

setTimeout allows to run a function once after the interval of time.


The syntax:



let timerId = setTimeout(func|code, delay[, arg1, arg2...])


func|code -  Function or a string of code to execute. Mostly, this will be a function. But some peoples may pass a string of code and its not recommended. The reason I have mentioned in Javascript interview section.

delay -  The delay before run, should be mentioned in milliseconds (1000 ms = 1 second).

arg1, arg2…  - arguments.

Simple Example:



1
2
3
4
5
function sayHi(welcomeMsg, user) {
  alert( welcomeMsg + ', ' + user );
}

setTimeout(sayHi, 5000, "Hello", "Raj"); // Hello, Raj

Explanation:

The sayHi method will be called after 5 seconds. Just compare this example with syntax. Hope you got it.

Note:

Do not pass like sayHi(). You should pass always method name only like sayHi without brackets.





Friday, April 27, 2018

Named Function Expression - NFE

Named Function Expression (NFE)  - We are giving a name to Function Expressions.

Before going into NFE, we should understand what is Ordinary Function Expression. Below is example,


let sayTest = function(one) {
  alert(one);
};

Now just add a name to that, (NFE).


let sayTest = function yourName(one) {
  alert(one);
};

It looks like very simple. But everything is designed for some reason. Let check why we are giving name like this?


1. It allows the function to reference itself internally.

2. It will not be visible to outside of the function.


let sayTest = function yourName(one) {
  if (one) {
    alert(one);
  } else {
    yourName("Guest"); // use yourName to re-call itself
  }
};

sayTest(); // Guest

// Error here
yourName(); // Error Here - not visible outside of the function


Come to our final main concept. Why we want this NFE. See below example,


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
let sayHi = function yourName(one) {
  if (one) {
    alert(`Hello, ${one}`);
  } else {
    yourName("Guest");  // Because of this line, this code working
    //sayHi ("Guest"); // This will not work.
  }
};

let welcome = sayHi;
sayHi = null;

welcome(); // nested call works here perfectly

Explanation :

1. Here line number 1, yourName is your NFE. 

2. You have used this name inside line number 5.

3. Suppose if you change the line number 5 to like sayHi("Guest"), will throw an error. Why ?

4. Because line number 10, sayHi was assigned to null. So this will be reflected to line number 9 too. So error will be thrown. (There is no sayHi function).

5. To solve that, we should add NFE , Because internal call possible in NFE.





Function Object with Custom Properties

We can add our own custom properties with function object.

Below example will explain you How do we use custom property with function object.


function countTest() {
  alert("Hi");

  countTest.counter++;
}
countTest.counter = 0; // initial value

countTest(); // Hi
countTest(); // Hi

alert( `Called ${countTest.counter} times` ); // Called 2 times

Explanation :

We are calling countTest function at two times. So while calling at every time counter (custom property) will be executed and returning 2 in alert.


Function object - length property

Using length property with function object, will return how many parameters the function using.

Example:


function first(a) {}
function second(a, b) {}
function multiple(a, b, ...more) {}

alert(first.length); // 1
alert(second.length); // 2
alert(multiple.length); // 2

Note: The last one, multiple function showing parameter length as 2. Because rest parameters(...) will not be calculated.


Thursday, April 26, 2018

Function Object - name property


Function objects contain some properties.

1. name property

We can access a function’s name with the help of the “name” property.


function testFunctionName() {
  alert("Hi");
}

alert(testFunctionName.name); //testFunctionName


let sayHi = function() {
  alert("Hi");
}

alert(sayHi.name); // sayHi

Above code, you can see we are getting the function name with the help of name property.


It will work with function which is placed inside object too. See below to understand further,


let user = {

  sayHi() {
    // ...
  },

  sayWelcome: function() {
    // ...
  }

}

alert(user.sayHi.name); // sayHi
alert(user.sayWelcome.name); // sayWelcome


Note: Suppose if there is no name for function then empty string will be returned.






Global Object (Window)

Global object is nothing but referring "window" only. The same will be called in node js as "global". For other frameworks it may have different name.

What it will do ?

It will provides you to access the built-in functions and values and provides access to the global Function Declarations and var variables.

Note: let and const is different from this. Declaring with var only we can consider as global.



var phrase = "Hello Test";

function sayHi() {
  alert(phrase);
}

// can read from window
alert( window.phrase ); // Hello Test
alert( window.sayHi ); // function sayHi() { alert(phrase); }


Wednesday, April 18, 2018

IIFE explanation with closure

Simple example for IIFE with closure explanation:


var MyClosureTest = (function (){
  var WelcomeMessage = 'Welcome to IIFE with Closure example';
  return {
    getWelcomeMessage: function () { return WelcomeMessage;},
    setWelcomeMessage: function (message) { WelcomeMessage = message}
  }
}());


Explanation:

Here,  We are not assigning a function to MyClosureTest. We want the result of invoking that function to MyClosureTest.

Important is, see at end - we added () in the last line.(IIFE).

If I want to get the WelcomeMessage then I can use getWelcomeMessage and it will work.  The below line will print our message.


console.log(MyClosureTest.getWelcomeMessage()); //Welcome to IIFE with Closure example

But following way would not work:


console.log(MyClosureTest.WelcomeMessage); 
// undefined

But you can set an get the expected message result:


MyClosureTest.setWelcomeMessage('I understood IIFE and closure');
console.log(MyClosureTest.getWelcomeMessage()); 
//I understood IIFE and closure






Self Invoking function | Immediately Invoked Function Expressions

Remember the below , this is the simple and best example for IIFE (Immediately Invoked Function Expressions).


(function () {
  // body of the function
}());

An another way for IIFE


(function () {
  // body
})();


It will be invoked automatically without being called. You must add parentheses(based on above two - I prefer second one ) in starting of the function and end of the function to express that it is a function expression.

How it is work ?

At the end we have added (), this is the reason its calling automatically. So remember adding () this at end is must. So that IIFE will work for you.

Why do we want to use this?

Most of the time for the below two reasons, we are using IIFE.

1. For Better namespace management

2. Closures

Next chapter we can see a good example about closures with IIFE. 





Tuesday, April 17, 2018

Spread operator

Spread operator to the opposite job of Rest parameter.

Below all examples combined together, please check one by one. So that you can understand it easily.


// Normal way - will not work
let arr = [7, 5, 4];
alert( Math.max(arr) ); // NaN


//Could work with spread operator
let arr = [7, 5, 4];
alert( Math.max(...arr) ); // 7 (spread turns array into a list of arguments)


//Multiple iterables array
let arr1 = [1, -2, 6, 5];
let arr2 = [8, 9, -8, 7];

alert( Math.max(...arr1, ...arr2) ); // 9



//Combined
let arr1 = [1, -2, 6, 5];
let arr2 = [8, 9, -8, 7];

alert( Math.max(3, ...arr1, 2, ...arr2, 52, 56) ); // 56



//Merging array is easy
let arr = [3, 5, 1, 4, 6, 8];
let arr2 = [8, 9, 15, 2, 1, 7, 3];

let merged = [0, ...arr, 2, ...arr2];

alert(merged); // 0,3,5,1,4,6,8,2,8,9,15,2,1,7,3


// String into array of characters
let str = "Hello";

alert( [...str] ); // H,e,l,l,o








Monday, April 16, 2018

The “arguments” variable

Actually rest parameters are available from ES6 on wards only. So if you you want the same behavior of Rest parameters in older than ES6, you should use "arguments".

Below example may tell you more clearly.


function showName() {
  alert( arguments.length );
  alert( arguments[0] );
  alert( arguments[1] );

  // Iteration also possible here
  // for(let arg of arguments) alert(arg);
}

// 2, Test1, Test2
showName("Test1", "Test2");

// 1, Ilakiya, undefined (Because no second argument)
showName("Ilakiya");

From the above code, we are calling showName method twice. While calling at first time we are passing two parameters.  So length is 2 and alert showing two parameters.

But while calling second showName function, we are passing only one parameter. So that , alert showing length as 1 and second parameter as undefined. Hope you got it.

Things to Remember:
              1. arguments is like an array , but it will not support array method . So you cannot use arguments.map() with this.

              2. Arrow functions do not have "arguments".





Rest parameters ...


A function can be called with any number of arguments. What is this means? Assume that you one simple sum function which accept two parameters. So you can pass those two parameters easily. But Suppose if it is more than 5 parameters or more than 10 parameters. You will get lazy to pass manually, right ? To avoid that use rest parameter.

Simple Example I:
function sumAll(...args) { // args is the name for the array
  let sum = 0;

  for (let arg of args) sum += arg;

  return sum;
}

alert( sumAll(1) ); // 1
alert( sumAll(1, 2) ); // 3
alert( sumAll(1, 2, 3) ); // 6

The rest parameters should be mentioned as three dots .... Here ...args is array which have all of your arguments.

Suppose if you dont want all n parameters as ...args, you can give first two as manual and remainig all as ...args.

Simple Example II:

function showName(firstName, lastName, ...titles) {
  alert( firstName + ' ' + lastName ); // TestFirstName TestLastName

  // the rest go into titles array
  // i.e. titles = ["ArrayFirst", "ArraySecond"]
  alert( titles[0] ); // ArrayFirst
  alert( titles[1] ); // ArraySecond
  alert( titles.length ); // 2
}

showName("TestFirstName", "TestLastName", "ArrayFirst", "ArraySecond");


Note: Remember, the ...rest must always be last.






JSON.parse


Whenever you are receiving data from a server, the data is may be a string. So to make the data as JS object we should use JSON.parse().


var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
console.log(obj); // Output will be in object format

var text = '{ "name":"John", "birth":"1986-12-10", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

console.log(obj);

Explanation:
     Initially we have passed a string value into the parse method. So that now it will become an object.

In the third line, same concept we have used like line number 1 and 2. But after parse, we have modified birth date property. So now the Date will be added like correct date format.


JSON Reviver function:

The Reviver parameter is a function which will check each property, before returning the value.


var text = '{ "name":"John", "birthDate":"1986-12-10", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
    if (key == "birthDate") {
        return new Date(value);
    } else {
        return value;
    }});


We are checking here for date, because we need to convert as a proper date format, not in string format. If you are not using parse reviver function, still you will use date as string only.
Hope you got it.





Custom - toJSON

Example I:


See the below example to understand custom toJson concepts. (Built in toJSON)

let Test = {
  number: 23
};

let TestingDate = {
  title: "DateTest",
  date: new Date(Date.UTC(2018, 0, 1)),
  Test
};

alert( JSON.stringify(TestingDate) );
/*
  {
    "title":"DateTest",
    "date":"2018-01-01T00:00:00.000Z",  // (1)
    "Test": {"number":23}               // (2)
  }
*/

Explanation:

        Here Date is showing perfectly after json convert. Because all dates have a built-in toJSON method which returns the correct string.

Example II: (custom toJSON)




let CustomCheck = {
  number: 23,
  toJSON() {
    return this.number;
  }
};

let CustomCheckTest = {
  title: "Something",
  CustomCheck
};

alert( JSON.stringify(CustomCheck) ); // 23

alert( JSON.stringify(CustomCheckTest) );
/*
  {
    "title":"Something",
    "CustomCheck": 23
  }
*/

Explanation:

This example is different, as we have mentioned toJSON separately. Means, we are not using in built toJSON.

In the initial customCheck object we have returned the number 23. So whenever you are using CustomCheck object , it will provide you 23.






What are the specific properties skipped by stringify

Some of JavaScript-specific object properties are skipped by JSON.stringify.

What are those ?

1. Function properties - means methods
2. Symbolic properties.
3. Properties that store undefined.


let user = {
  sayHi() { // ignored
    alert("Hello World");
  },
  [Symbol("id")]: 123, // ignored
  something: undefined // ignored
};

alert( JSON.stringify(user) ); // {} (empty object)



However, another good here is, nested objects are supported and converted automatically.


let testNestedObjects = {
  title: "NestedCheck",
  test1: {
    number: 123,
    participants: ["test25", "test26"]
  }
};

alert( JSON.stringify(testNestedObjects) );

Output:

{
  "title":"NestedCheck",
  "test1":{"number":123,"participants":["test25","test26"]},
}








JSON methods

Generally we will use JSON for sending data over the network like Rest web service call etc.,

We can see some important methods here.

1. JSON.stringify -  to convert objects into JSON.

2. JSON.parse      -  to convert JSON back into an object.



let student = {
  name: 'Rajini',
  age: 30,
  isAdmin: false,
  courses: ['css', 'js']
};

let json = JSON.stringify(student);

alert(typeof json); // Its String now.

alert(json);
/* JSON-encoded object:
{
  "name": "Rajini",
  "age": 30,
  "isAdmin": false,
  "courses": ["css", "js"]
}
*/


Things to Remember Here:

1. Strings use double quotes. No single quotes or backticks in JSON. So 'Rajini' becomes "Rajini".

2. Object property names are double-quoted also. That’s obligatory. So age:30 becomes "age":30.

3. JSON.stringify can be applied to primitives also.


JSON supported types are:

Objects { ... }
Arrays [ ... ]
Primitives:
strings,
numbers,
boolean values true/false,
null.







Object destructuring

We can use destructuring assignment for objects also.

Syntax:
let {var1, var2} = {var1:…, var2:…}

Right side is an existing object which that we want to split into variables. Left side is our pattern to split variables.

Basic Example I:



let options = {
  title: "MasterPage",
  width: 100,
  height: 200
};

let {title, width, height} = options;

alert(title);  // MasterPage
alert(width);  // 100
alert(height); // 200

Internally its uses like , options.title, options.width and options.height. Hope you got it.
and order does not matter here. Anywhere it will work.

Example II:



let options = {
  title: "MasterPage",
  height: 200,
  width: 100
};

let {title, width, height} = options;

alert(title);  // MasterPage
alert(width);  // 100
alert(height); // 200

Above order was changed, still its working perfectly.

Rest Operator:

Below we have used Rest operator with object. So other than title, remaining will come under rest. See below code.


let options = {
  title: "MasterPage",
  height: 200,
  width: 100
};

let {title, ...rest} = options;

// now title="MasterPage", rest={height: 200, width: 100}
alert(rest.height);  // 200
alert(rest.width);   // 100







Destructuring assignment

We all know, most used data structures in JavaScript are Object and Array.

Destructuring asis a special syntax that allows us to “unpack” arrays or objects into a bunch of variables.

Why its allowing? Since they are more convenient. Most of the time we want to work with complex functions that have a lot of parameters, default values etc.,

Array destructuring:



let arr = ["Ilakiya", "Kannika"]

// destructuring assignment
let [firstName, surname] = arr;

alert(firstName); // Ilakiya
alert(surname);  // Kannika

See, Its very compatible. Its coming with ES6.

Here is another trick for ignoring first elements. See below...


let [, , title] = ["Test1", "Test2", "Test3", "Test4"];

alert( title ); // Test3

As you have put comma for two times, first two elements not considered here.

You can more play with this.. See below.


let user = {};
[user.name, user.surname] = "Ilyakiya My Love".split(' ');

alert(user.name); // Ilyakiya


Rest ...

You can mention multiple at a time , then go with “the rest” using three dots "..."


let [name1, name2, ...rest] = ["Test1", "Test2", "Test10", "Test11"];

alert(name1); // Test1
alert(name2); // Test2

alert(rest[0]); // Test10
alert(rest[1]); // Test11
alert(rest.length); // 2


WeakMap and WeakSet

WeakMap and WeakSet is little different because it does not prevent from memory. You may understand it after seeing the example.

We can not use keys as primitives in weakmap.


let weakMap = new WeakMap();

let obj = {};

weakMap.set(obj, "ok"); // works fine (object key)

weakMap.set("test", "Whoops"); // Error, because "test" is a primitive

If you are trying to use primitives in weakmap, simply it will through an error. (above example).

Example II:


let john = { name: "John" };

let weakMap = new WeakMap();
weakMap.set(john, "...");

john = null; // overwrite the reference

// john is removed from memory!

alert(john); //null

Below is the main part of weakmap. Furthermore , you can not access john after set it to null.

Weak map have some limitation in methods, because of some technical reason. Because, we should allow javascript engine to do the clean work. Means, clean should do immediately or later or parallel.

1. weakMap.get(key)

2. weakMap.set(key, value)

3. weakMap.delete(key, value)

4. weakMap.has(key)

WeakSet also same like weak map.

JavaScript Set

A Set is a collection of values, where each value may occur only once.

Its main methods are:

new Set(iterable)  –  creates the set, optionally from an array of values.
set.add(value)       –  adds a value, returns the set itself.
set.delete(value)  –  removes the value, returns true if value existed at the moment of the call, else false.
set.has(value)       –   returns true if the value exists in the set, else false.
set.clear()             –   clear everything from the set.
set.size                 –   the elements count.

Example I:


let set = new Set();

let test1 = { name: "test1" };
let test2 = { name: "test2" };
let test3 = { name: "test3" };

set.add(test1);
set.add(test2);
set.add(test3);
set.add(test1);
set.add(test3);

// Unique only allowed
alert( set.size ); // 3

for (let user of set) {
  alert(user.name); // test1 (then test2 and test3)
}

For uniqueness, you can go ahead with set.

Set Iteration :

Below are supported methods with set iterator.

set.keys() – returns an iterable object for values.
set.values() – same as set.keys, for compatibility with Map.
set.entries() – returns an iterable object for entries [value, value], exists for compatibility with Map.

Note: Map also have the same above.



let setExample = new Set(["oranges", "apples", "Mango"]);

for (let value of setExample) alert(value);

// the same with ES6 for each
setExample.forEach((value, valueAgain, set) => {
  alert(value);
});






Iteration Map

Consider I am passing an array to the map like below,


// array of [key, value] pairs
let map = new Map([
  ['1',  'stringOne'],
  [1,    'number1'],
  [true, 'booleanTrue']
]);

Object.entries(obj) is an inbuilt method  which returns an array of key/value pairs for an object with same format.

We can an initialize a map from an object like below,


let map = new Map(Object.entries({
  name: "Tester",
  age: 30
}));

Here, Object.entries returns the array of key-value pairs.

Output:
 [ ["name","Tester"], ["age", 30] ].

Iterate on Map:

There are 3 methods, we can use..

map.keys() – returns an iterable for keys,
map.values() – returns an iterable for values,
map.entries() – returns an iterable for entries [key, value] and it is used by default in for..of.

Example I :



let sportsMap = new Map([
  ['Cricket', 500],
  ['Football', 350],
  ['WWE',    50]
]);

// iterate over keys (vegetables)
for (let sport of sportsMap.keys()) {
  alert(sport); // cricket, Football, WWE
}

// iterate over values (amounts)
for (let fee of sportsMap.values()) {
  alert(fee); // 500, 350, 50
}

// iterate over [key, value] entries
for (let entry of sportsMap) { // the same as of recipeMap.entries()
  alert(entry); // cricket,500 (and so on)
}

Note: Map preserves this insertion order


ForEach with ES6 :

Map has a built-in forEach method, similar to Array...

Example II


sportsMap.forEach( (value, key, map) => {
  alert(`${key}: ${value}`); // cricket: 500 etc
});







Thursday, April 12, 2018

How to use object as Keys in Map

We can also use object as key in map.

Note: ES6 map is different. Do not make confuse yourself.

Example I:


let testObject = { name: "TestObject With Map" };

let testMap = new Map();

testMap.set(testObject, 123);

alert( testMap.get(testObject) ); // 123

Here testObject is the simple normal object which I used as key in map.

How Map comparing keys ?

Map uses the algorithm SameValueZero (same as strict equality === ).

We can also do the chaining operation with map. See below example,



testMap.set('1', 'stringOne')
       .set(1, 'number1')
       .set(true, 'booleanTrue');


Like this you can add n number of times.







Important methods in Map with example

Map is like key value pair concept (like an Object). But Map allows keys as any type. Remember object allows only string key.

Note: ES6 map is different. Do not make confuse yourself.

Main methods are below,

      new Map() – creates the map.

     map.set(key, value) – stores key and value.

     map.get(key) – returns the value by the key. Suppose If key doesn’t exist undefined will be  returned.

     map.has(key) – returns true if the key exists, else false will be returned.

     map.delete(key) – removes the value by the key.

     map.clear() – clears the map.

     map.size – returns the current element count.

Simple Example I:



let map = new Map();

map.set('1', 'stringOne');   // a string key
map.set(1, 'number1');     // a numeric key
map.set(true, 'booleanValueTrue'); // a boolean key

alert( map.get(1)   ); // 'number1'
alert( map.get('1') ); // 'stringOne'
alert( map.get(true) ); // 'booleanValueTrue
alert( map.size ); // 3


Note: See the above example, Keys are not converted to string.





Array - Split and join

A delimiter should be used with split method and its an optional parameter.

Syntax: 
string.split(separator, limit)


separator - Optional. Specifies the character, or the regular expression, to use for splitting the string.

limit - Optional. An integer that specifies the number of splits. No item will be take care after specified limit.

Example I:



let names = 'Test, Test1, Test3';

let arr = names.split(', ');

for (let name of arr) {
  alert( name ); // Test Test1 Test3
}

Example II:


var strTest = "How are you Baby?";
 var resTest = str.split(" ", 3);
 alert(resTest); // How,are,you

Example III:

Nothing specified then , below result you will get.

let str = "test";

alert( str.split('') ); // t,e,s,t


Join Method:

The reverse of split is called join method. Means, opposite to reverse.


let arr = ['Test1', 'Test2', 'Test3'];

let str = arr.join(';');

alert( str ); //Test1;Test2;Test3







Array Sort - Reverse

To sort an array in reverse, we can use reverse method directly. See below example,

1. Reverse an Integer array


let arr = [1, 2, 3, 4, 5];
arr.reverse();

alert( arr ); // 5,4,3,2,1

2. Reverse an string array


var fruitsTest = ["Banana", "Orange", "Apple", "Mango"];
fruitsTest.reverse();

Note: Reverse means , just reverse( End to start) the output. not any order.

Wednesday, April 11, 2018

Array ReOrdering - Sort


        In Javascript , the items are sorted as strings by default. So if you try to sort an array with have integer value, it will return incorrect result. See below example,


let arr = [ 1, 2, 7,15, 18 ];

arr.sort();

alert( arr );  // 1,15,18,2,7(Wrong Result)

The above example returns a wrong result. Because as I said earlier, sorted by string is default.

Remember, internally it will convert as string.

1. Classical Trick


function compareNumeric(a, b) {
  if (a > b) return 1;
  if (a == b) return 0;
  if (a < b) return -1;
}

let arr = [ 1, 2, 15, 7, 19, 54, 87, 43 ];
arr.sort(compareNumeric);
alert(arr);  // 1,2,7,15,19,43,54,87

2. With simple comparison




let arrSort = [ 1, 2, 15, 76, 76, 34, 89, 12 ];

arrSort.sort(function(a, b) { return a - b; }); // Ascending

alert(arrSort);

Note: For descending use b-a.


3. Same with Arrow function




let arrSort = [ 1, 2, 15, 76, 76, 34, 89, 12 ];

arrSort.sort( (a, b) => a - b );

alert(arrSort);


Conclusion:

Here all the example is only for integer array. Suppose If you want to sort an string array, no need to worry about above logic. Simply you can call sort method directly.