Search This Blog

2021/01/29

 

In javascript there are console.log,console.debug,console.warn,console.error.so what each of this stands for


1) console.log : Black color text with no icon


2) console.info: Blue color text with icon


3) console.debug : Pure black color text


4) console.warn :Yellow color text with icon


5) console.error : Red Color text with icon


for purpose of illustartion I created a index.html file with following code


<html>

<head>

</head>

<body>

<script>

console.log('console.log');

console.info('console.info');

console.debug('console.debug');

console.warn('console.warn');

console.error('console.error');

</script>

</body>

</html>

Here is how it looks on browser console.



     

Console.log & console.debug looks same. while console.info has addition icon to console,log.

2021/01/28

How to check pair of word are anagram in Javascript

 An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.[1] For example, the word anagram itself can be rearranged into nag a ram, also the word binary into brainy and the word adobe into abode.

How to check given pait of word anagram

function IsAnagram(string11,string22)
{
    //remove white spaces & make both word in same case
    string1 = string11.replace(/ /g,'').toUpperCase();
    string2 = string22.replace(/ /g,'').toUpperCase();

    if(string1.length != string2.length)
    {
        return false;
    }else{

       let str1 =  [...string1];
       let str2 =  [...string2];

       str1 = str1.sort();
       str2 = str2.sort()

       string1 = str1.join('');
       string2 = str2.join('');

       if(string1 == string2)
       {
         return true;
       }else{
           return false;
       }

    }
}


console.log('"STOP" & "POST" combination is anagram :' + IsAnagram('STOP','POST'));

console.log('"FIRE" & "RIDE" combination is anagram :' + IsAnagram('FIRE','RIDE'));

console.log('"New York Times" & "monkeys write" combination is anagram :' + IsAnagram('New York Times','monkeys write'));


Output:
"STOP" & "POST" combination is anagram :true
"FIRE" & "RIDE" combination is anagram :false
"New York Times" & "monkeys write" combination is anagram :true

2021/01/10

Reading Files from Path Array ensure synchronous Nature:

we have a fileNames array which contain path to files read.Used bluebird to promisify fs module which makes us available promisified version readFileAsync of readFile.

Created three files 1.txt,2.txt and 3.txt with one two & three inside them inside data folder.Added one,two,three as text inside these three files.

Async Way:


var Promise = require("bluebird");

var fileNames =["data/1.txt","data/2.txt","data/3.txt"]

var fs = Promise.promisifyAll(require("fs"));


var promises = [];

console.log("Started");

for (var i = 0; i < fileNames.length; ++i) {

fs.readFileAsync(fileNames[i],'utf8').then(function(data){

console.log(data);

}).catch(function(err){

console.log(err);

})

}

console.log("Finished");


Output:

Started

Finished

two

one

three


Order of reading files is not maintained.


Using Promise.all


var Promise = require("bluebird");

var fileNames =["data/1.txt","data/2.txt","data/3.txt"]

var fs = Promise.promisifyAll(require("fs"));


console.log("Started");

var promises = [];

for (var i = 0; i < fileNames.length; ++i) {

promises.push(fs.readFileAsync(fileNames[i],'utf8'));

}

Promise.all(promises).then(function(result) {

console.log(result)

console.log("done");

});

console.log("Finished");


Output:

Started

Finished

[ 'one', 'two', 'three' ]

done


Response of reading three files get at once.


Synchronized Way:

var Promise = require("bluebird");

var fileNames =["data/1.txt","data/2.txt","data/3.txt"]

var fs = Promise.promisifyAll(require("fs"));


runLoop = async (cb)=>{

try{

let result =[];

for(let i=0;i < fileNames.length ;i++)

{

console.log("Fetching " + fileNames[i]) + "....";

await new Promise((resolve,reject)=>{

setTimeout(function(){

fs.readFileAsync(fileNames[i],'utf8').then(function(fileContent){

console.log("fileContent",fileContent)

result.push(fileContent)

resolve()

}).catch(function(err){

reject(err)

console.log("err",err);

//throw err;

})

}, 0);

});

}

cb(result)

}catch(ep)

{

console.log("ep",ep);

}

}


runLoop(function(data){

console.log("data",data);

})

 

Output:

Fetching data/1.txt

fileContent one

Fetching data/2.txt

fileContent two

Fetching data/3.txt

fileContent three

data [ 'one', 'two', 'three' ]



reads files in order they present in loop.I tried increasing content of 1.txt yet order remain same.


Synchronous For loop :

Loop can be made to wait until promise resolve which is put inside settimeout so as to wait for 2000 milliseconds.Each array item is printed after 2000 milliseconds delay.


let arr =[10,20,30,40,50,60,70,80,90]


runLoop = async ()=>{

for(let i=0;i < arr.length ;i++)

{

await new Promise((resolve,reject)=>{

setTimeout(function(){

resolve()

console.log(arr[i]);

}, 2000);

})

}

}


runLoop();


Output:

sangram@sangram-HP-Laptop-15-bs0xx:~/projects/nodejs/promise-all$ node loop.js

10

20

30

40

50

60

70

80

90


Here 10,20,30 ... these are printed after waiting for 2000 milliseconds for each iteration.

Promise.all in Node.js

Promise.all() static method used to aggregate results from multiple asynchronous operations.

The Promise.all() static method accepts a list of Promises and returns a Promise that:

  • resolves when every input Promise has resolved or

  • rejected when any of the input Promise has rejected.

Example 1:

const p1 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The first promise has resolved');


resolve(10);

}, 1 * 1000);


});


const p2 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The second promise has resolved');

resolve(20);

}, 2 * 1000);

});


const p3 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The third promise has resolved');

resolve(30);

}, 3 * 1000);

});


Promise.all([p1, p2, p3])

.then(results => {

const total = results.reduce((p, c) => {return p + c},0);



console.log(`Results: ${results}`);

console.log(`Total: ${total}`);

});



Output:

The first promise has resolved

The second promise has resolved

The third promise has resolved

Results: 10,20,30

Total: 60


Here all promises resolves.Result of promise.all is an array containing result of each members result .e.g. [10,20,30]


Example 2:

const p1 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The first promise has resolved');

resolve(10);

}, 1 * 1000);


});


const p2 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The second promise has rejected');

reject('Failed');

}, 2 * 1000);

});


const p3 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The third promise has resolved');

resolve(30);

}, 3 * 1000);

});


Promise.all([p1,p2, p3])

.then(function(results){

console.log(`Results: ${results}`);

}) // never execute

.catch(function(err){

console.log("err:",err);

});

Output:

The first promise has resolved

The second promise has rejected

err: Failed

The third promise has resolved




Here one promise get rejected so promise.all get rejected too.

2021/01/01

Immediately-invoked Function Expression (IIFE)

 An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created.

IIFEs are very useful because they don’t pollute the global object, and they are a simple way to isolate variables declarations.

Example 1:

(function (a)

{

console.log(a);

})(5)


Output:

5

or It can be defined as


(function() {

console.log("Hello from IIFE!");

}());


Output:

Hello from IIFE!



Assigning the IIFE to a variable stores the function's return value, not the function definition itself.

Example 2:

var func = (function ()

{

var a=10;

return a

})();

console.log(func)


output:

10


The variable within the expression can not be accessed from outside it.

Example 3:

var func = (function ()

{

var a=10;

return a

})();

console.log(a);



output:

ReferenceError: a is not defined


Another way of writing IIFE:

Example 4:

!function() {

console.log("Hello from IIFE!");

}();




Whenever JavaScript sees function keyword as the first word in a valid statement, it expects that a function definition is going to take place. So to stop this from happening, we are prefixing “!” in-front of the function keyword on line 1


The above variation can be used by replacing “!” with “+”, “-”, or even “~” as well. Basically any unary operator can be used.

e.g. following is also valid IIFE

Example 5:

~function() {

console.log("Hello from IIFE!");

}();


Example 6:


(function IIFE_initGame() {

// Private variables that no one has access to outside this IIFE

var lives;

var weapons;

init();


// Private function that no one has access to outside this IIFE

function init() {

lives = 5;

weapons = 10;

console.log(`lives: ${lives} and weapons: ${weapons}`);

}

}());


Output:

lives: 5 and weapons: 10


we have declared two variables inside the IIFE and they are private to that IIFE. No one outside the IIFE has access to them. Similarly, we have an init function that no one has access to outside the IIFE. But the init function can access those private variables.



How to make variable private in Javascript

Javascript does not have access modifier to be precise like other programming languages say Java.So How can we make a variable private.Let us see.

Consider following code snippet


//Immediately invoked function expression

let Person = (function()

{

let _age=0;

return {

firstName:"sangram",

lastName:"desai",

get age()

{

return _age;

},

set age(val)

{

_age = val

}

};

})()


//printing all accessible properties of object

for(let prop in Person)

{

console.log(prop);

}


console.log(Person.firstName)

console.log(Person.lastName)


//public properties

Person.age = 40;

console.log(Person.age)


//private variable

console.log(Person._age)



Output:

firstName

lastName

age

sangram

desai

40

undefined


Here _age is defined outside to make it private property.firstName & lastName are public properties of Person object.we defined age property using getter & setter syntax to access private property _age

We have printed all accessible properties of Person Object which happens to be

firstName

lastName

age


note _age is not there.

Then we try to directly print _age as follows


console.log(Person._age)


It comes out as undefined.

Getter & Setter in Javascript:

Es6 has functionality define property getter & setter.

Lets us see how we can do it.


Here is our code


let Person =

{

firstName:"sangram",

lastName:"desai",


get fullName()

{

return `${this.firstName} ${this.lastName}`;

},


set fullName(val)

{

let parts = val.split(' ');

this.firstName = parts[0];

this.lastName = parts[1];

}

};


console.log(Person.fullName);

Person.fullName = "Saurabh Ganguli"

console.log(Person.fullName);

 

Output:

sangram desai
Saurabh Ganguli

We created getter property fullName as follows


get fullName()

{

return `${this.firstName} ${this.lastName}`;

}


while setter fullname is defined as follows


set fullName(val)

{

let parts = val.split(' ');

this.firstName = parts[0];

this.lastName = parts[1];

}


we can access fullName as Person.fullName .

To set fullName a value we can do following

Person.fullName = "Saurabh Ganguli".