⏱ 0:01est. 30 min
Practice Nov 2021
var greet = function(name) {
return `Hi, ${name}`
}('Nishant')
console.log(greet);
3;
"I'm a string";
{
name: "John"
}
// IIFE
(function(name) {
console.log(name);
})('Testing IIFE');
// Closure
function greetSomeone(whattosay) {
return function (name) {
return `${whattosay}, ${name}`
}
}
console.log(greetSomeone('Hi')('Nishant'));
function buildFunction () {
const arryOfFunctions = [];
// to fix this change var to let
for (var index = 0; index < 3; index++) {
arryOfFunctions.push(function() {
console.log(index);
})
}
return arryOfFunctions;
}
var fs = buildFunction();
fs[0]();
fs[1]();
fs[2]();
function buildFunction3 () {
const arryOfFunctions = [];
for (let index = 0; index < 3; index++) {
arryOfFunctions.push(function() {
console.log(index);
})
}
return arryOfFunctions;
}
var fs3 = buildFunction3();
fs3[0]();
fs3[1]();
fs3[2]();
function buildFunction2 () {
const arryOfFunctions = [];
// to fix this change var to let
for (var index = 0; index < 3; index++) {
arryOfFunctions.push(function(index) {
console.log(index);
}(index))
}
return arryOfFunctions;
}
var fs2 = buildFunction2();
fs2[0];
fs2[1];
fs2[2];
// callback
function sayHiLater() {
setTimeout(() => {
console.log("hi");
}, 3000);
}
sayHiLater();
// bind
let person1 = {
first_name: 'Nishant',
last_name: 'Mendiratta',
getFullName: function () {
return `${this.first_name} ${this.last_name}`
}
}
const logFullName = function() {
console.log(this.getFullName());
}
// logFullName() // throws an error
const lName = logFullName.bind(person1); //Nishant Mendiratta
lName();
logFullName.call(person1); //Nishant Mendiratta
// currying binding (creating new copy of the function)
function multiply(a) {
return function (b) {
return a*b;
}
}
console.log(multiply(2)(3));
function multiply2(a,b) {
return a*b;
}
var multiplyBy2 = multiply2.bind(this, 2);
console.log(multiplyBy2(4));
// Function constructor
function Person() {
this.first_name = "John";
this.last_name = "Doe";
}
Person.prototype.getFullName = function () {
return `${this.first_name} ${this.last_name}`;
}
var john = new Person();
console.log(john); // {first_name: "John", last_name: "Doe"}
console.log(john.getFullName());
String.prototype.isLengthGreaterThan = function (limit) {
return this.length > limit;
}
console.log("hello".isLengthGreaterThan(3)); // true
console.log("he".isLengthGreaterThan(3)); // false`
// fetch data
function fetch(url) {
return new Promise(resolve => {
setTimeout(() => {
resolve(`dummy data for ${url}`)
}, Math.random() * 4000);
})
}
const BASE_API = 'https://localhost:3001/design/';
function createPromiseForCallImages() {
const imagePromises = [];
for (let index = 0; index < 10; index++) {
imagePromises.push(fetch(`${BASE_API}/${index}`))
}
return imagePromises;
}
function getAllImages() {
const imagePromises = createPromiseForCallImages();
Promise.all(imagePromises).then((response) => {
console.log(response)
return response;
}).then(() => {
console.log('done');
}).catch((e) => {
throw new Error("Faoled to fetch");
})
}
getAllImages();
function fetchDesigns() {
return new Promise(resolve => {
setTimeout(() => resolve({
designId: 1,
shapes: [
{ shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 }},
{ shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 }},
{ shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 }},
{ shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 }}
]
}
), Math.random() * 5000);
});
}
const promisesShapes = [fetchDesigns()]; // use loop to create
// const prob1= [
// {
// designId: 1,
// shapes: [
// { shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 }},
// { shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 }},
// { shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 }},
// { shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 }}
// ]
// },
// {
// designId: 2,
// shapes: [
// { shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 }},
// { shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 }},
// { shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 }},
// { shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 }}
// ]
// }
// ]
function getAverageOfShapes() {
Promise.all(promisesShapes).then((response) => {
return response
}).then(computeAverage).then((result) => {
// }).then((result) => {
console.log('result', result);
}).catch((e) => {
throw new Error("Failed to fetch");
})
}
function computeAverage(designInformation) {
console.log('designInformation')
const computedResult = designInformation.map((design) => {
console.log('design', design)
let totalR = 0;
let totalG = 0;
let totalB = 0;
const totalShapes = design.shapes.length;
design.shapes.forEach(({color}) => {
totalR += color.r;
totalG += color.g;
totalB += color.b;
})
design['redAvg'] = totalR/totalShapes;
design['greenAvg'] = totalG/totalShapes;
design['blueAvg'] = totalB/totalShapes;
return design;
});
// console.log('computedResult', computedResult)
return computedResult;
}
getAverageOfShapes();
// const intervals = [[3, 5], [1, 3], [7, 9]]; // [ 1, 5 ], [ 7, 9 ] ]
const intervals = [[7, 10], [1, 5], [12, 13], [2, 6], [7, 11]]; // [[[1, 6], [7, 11], [12, 13]]
function mergeIntervals(intervals) {
intervals.sort((a,b) => a[0]-b[0])
const result = [];
intervals.forEach((interval, index) => {
let meergedInterval = interval;
if (index+1<intervals.length) {
let nextInterval = intervals[index+1]
if (meergedInterval[1]>=nextInterval[0]) {
nextInterval[0] = Math.min(meergedInterval[0], nextInterval[0]);
nextInterval[1] = Math.max(meergedInterval[1], nextInterval[1]);
} else {
result.push(meergedInterval)
}
} else {
result.push(meergedInterval)
}
})
console.log(result)
}
mergeIntervals(intervals);
function debounced(func) {
let timer = null;
return function (e) {
clearTimeout(timer);
timer = setTimeout(() => {
func(e);
}, 3000)
}
}
function debounce(func) {
let timer = null;
return function(e) {
clearTimeout(timmer);
timer = setTimeout (() => {
func(e);
}, 4000)
}
}
function notAClosure(anotherShortLivedVariable) {
return anotherShortLivedVariable;
}
console.log(notAClosure('hi'))
console.log(notAClosure('hi1'))
console.log(notAClosure('hi2'))
function aClosure(longLivedVariable) {
let innerFunction = () => {
return longLivedVariable
}
return innerFunction
}
const closure = aClosure("body");
console.log(closure())
console.log(closure())
function cat(name) {
return {
sayName: () => {
return name
}
}
}
const msFloofy = cat("Madam Fluff");
console.log(msFloofy.sayName())
console.log(msFloofy.sayName())
var whiskers = cat('Whiskers');
console.log(whiskers.sayName()) // returns 'Whiskers'
let a = "hell this is nishant"
a[1] = "b"
console.log(a[1]) //"e"
const b = () => {}
let c = {a:1, b:2}
let y = c
y.a = 42;
delete y.b
console.log(c) // 42
var arr = [];
arr[0] = 'a';
arr[1] = 'b';
arr.foo = 'c';
console.log(arr.length); //2
const debounce = (func, delay) => {
let timeout = null;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args)
}, delay)
}
}
const expensive = () => {
console.log("expensive");
}
// window.addEventListener('resize', expensive);
// throttle -- This better expensive function will use throttling and some limit.
const betterExpensiveFn = throttle(expensive, 10);
function throttle (fn, limit) {
let flag = true;
return function () {
if (flag) {
const context = this;
const args = arguments;
fn.apply(context, args);
flag = false;
setTimeout(() => {
flag = true;
}, limit)
}
}
}
function throttle (fn, limit) {
let flag = true;
return function () {
const context = this;
const args = arguments;
if (flag) {
fn.apply(context, args);
flag = false;
setTimeout(() => {
flag = true;
}, limit)
}
}
}
//using better fn
// window.addEventListener('resize', betterExpensiveFn);
const debounceer = function (fn, limit) {
let timer;
return function () {
const ctx = this;
const arg = arguments;
clearTimeout(timer); // clearing timer whenever a new function is made, and 300 ms hasn't been passed
// stop calling this method if key-stroke happen in between
timer = setTimeout(() =>{
fn.apply(ctx, arg); //fn() //getData();
}, limit);
}
};
const expensiveInput = function () {
console.log('expensive input');
};
const betterSearchFn = debounceer(expensiveInput, 500);
betterSearchFn();
betterSearchFn();
betterSearchFn();
betterSearchFn();
function sum(a) {
return function(b) {
if (b) {
return sum(a+b);
}
return a;
}
}
console.log('sum', sum(1)(2)());
function logFetch() {
return new Promise((resolve, reject) => {
resolve('hello from log fetch');
// reject(new Error('Woops!!'));
})
}
logFetch().then((response) => {
console.log('response', response)
}).catch((error) => {
console.log('error', error)
})
function loadScript(src) {
return new Promise((resolve, reject) => {
let script = document.createElement('script');
script.src = src;
script.onload = () => resolve(script);
script.onerror = () => reject(new Error(`Failed to load ${src}`));
document.head.append(script);
})
}
let promiseLoadScript = loadScript("https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js");
promiseLoadScript.then(
script => alert(`${script.src} is loaded!`),
error => alert(`Error: ${error.message}`)
);
promiseLoadScript.then(script => alert('Another handler...'));
// create circle
function go() {
showCircle(150, 150, 100).then(div => {
div.classList.add('message-ball');
div.append("Hello, world!");
});
}
function showCircle(cx, cy, radius) {
let div = document.createElement('div');
div.style.width = 0;
div.style.height = 0;
div.style.left = `${cx}px`;
div.style.top = `${cy}px`;
div.className = 'circle';
document.body.append(div);
return new Promise((resolve, reject) => {
setTimeout(() => {
div.style.width = radius*2+'px';
div.style.height = radius*2+'px';
div.addEventListener('transitionend', function handler() {
div.removeEventListener('transitionend', handler);
resolve(div);
})
}, 1000)
})
}
// Async await
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Hello",))
})
let result = await promise;
console.log(result);
}
f()
// promise chaining
new Promise(function (resolve, reject) {
setTimeout(() => resolve(1), 1000); // (*)
}).then(function(result) {
console.log(result+1);
}).finally(function() {
console.log('done')
})
// promise loading image
function loadJsonWithPromise() {
return fetch(url).then(response => response.json());
}
// promise loading image
function loadGithubUser(name) {
return loadJsonWithPromise(`https://api.github.com/users/${name}`)
}
// promise loading image
function showAvatar(githubUser) {
return new Promise(function(resolve, reject) {
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = 'promise-avatar';
document.body.append(img);
setTimeout(() => {
img.remove();
resolve(githubUser)
}, 2000)
})
}
// promise loading image
loadJsonWithPromise('/article/promise-chaining/user.json')
.then(user => loadGithubUser(user.name))
.then(showAvatar)
.then(githubUser => alert(`Finished showing ${githubUser.name}`));
// ...
// async/await loading image
async function showAvatarWithAsync() {
// read the json
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
// read the user
let githubUserResponse = await fetch(`https://api.github.com/users/${user.name}`);
let githubUser = await githubUserResponse.json();
// show the avatar
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = 'await-avatar';
document.body.append(img);
// clear this image after 3 seconds
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
img.remove();
return githubUser;
}
// bind
let basic = {
name: 'Nishant',
age: '32'
}
function callMe(city) {
console.log('Hi! my name is ' + this.name + ' and my age is ' + this.age + ' and my city is ' + arguments[0] + ' and state is ' + arguments[1]);
}
let callBinded = callMe.bind(basic, 'Delhi');
callBinded('DL')
// polyfill bind
Function.prototype.inCompleteMyBind = function (context) {
let fn = this;
console.log('this', this)
console.log('context', context)
return function () {
fn.call(context)
}
}
Function.prototype.myBind = function (context, ...args1) {
let fn = this;
return function (...args2) {
fn.apply(context, [...args1, ...args2]);
}
}
let callCustomBbind = callMe.myBind(basic, 'Delhi');
callCustomBbind('DL');
// reduce
let nums = [1,2,3,5,5]
let sum = nums.reduce(function (accumulator, item, index, array) {
return accumulator+item;
}, 0)
console.log(sum);
let arrayToFlat = [1,2,[3],[[4]],[[[5]]]]
function flatten (arr) {
return arr.reduce(function (flatAccumulator, item) {
return flatAccumulator.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}
console.log(flatten(arrayToFlat));
let arrToReverse = [1, 2, 3, 4];
console.log(arrToReverse.reverse());
let arrToReverse1 = [1, 2, 3, 4];
let reversedArray = [];
arrToReverse1.forEach(element => {
reversedArray.unshift(element);
})
console.log(reversedArray);
let arrToReverse2 = [1, 2, 3, 4];
for(let i=0; i<arrToReverse2.length/2; i++) {
[arrToReverse2[i], arrToReverse2[arrToReverse2.length-i-1]] = [arrToReverse2[arrToReverse2.length-i-1], arrToReverse2[i]];
}
console.log(arrToReverse2);
// Async
async function AsyncF() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
return resolve("done!")
}, 1000)
})
let a = await promise;
console.log(a);
return a;
}
AsyncF().then(console.log)
async function showAvatarWithAsync1() {
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
let githubUser = await githubResponse.json();
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = 'promise-avatar-example';
document.body.append(img);
await new Promise((resolve, reject) => {
setTimeout(resolve, 1000);
})
img.remove();
return githubUser;
}
let promise1 = new Promise((resolve, reject) => {
resolve('hi')
})
promise1.then((result) => console.log(result));
let promise2 = new Promise((resolve, reject) => {
setTimeout(()=> {
resolve('hi')
}, 3000)
})
promise2.then((result) => console.log(result));
let promise3 = new Promise((resolve, reject) => {
// setTimeout(()=> {
// resolve('hi')
reject(new Error('Whoops!!'))
// }, 3000)
})
promise3.finally(() => {
console.log('finally')
}).then(() => console.log('hi')).catch((e) => {
console.log('err', e);
});
let personTestObj = {
name: 'Nishant',
lastname: 'Mendiratta',
age: '33',
getFullName: function () {
// console.log(this); // window
return this.name
}
}
function PersonTest(state, country) {
return console.log(`${this.getFullName()}`, state, country);
// return console.log(`${this.name} ${this.age}`);
}
// BIND
console.log(personTestObj.getFullName()) // Nishant
PersonTest.bind(personTestObj)('Delhi', 'IN'); // Nishant
let p = PersonTest.bind(personTestObj);
p('Delhi', 'IN') // Nishant, 'Delhi', 'IN'
// CALL
PersonTest.call(personTestObj, 'Delhi', 'IN') // Nishant Delhi IN
// Apply
PersonTest.apply(personTestObj,['Delhi', 'IN']) // Nishant Delhi IN
Function.prototype.polifyllOFBind = function (context, ...args1) {
let fn = this;
return function() {
fn.call(context);
}
}
PersonTest.polifyllOFBind(personTestObj)(); // Nishant undefined undefined
Function.prototype.polifyllOFBindComplete = function (context) {
let fn = this;
return function(...args1) {
fn.apply(context, [...args1]);
}
}
PersonTest.polifyllOFBindComplete(personTestObj)('Delhi', 'IN'); // Nishant Delhi IN
let arrToReverse = [1, 2, 3, 4];
console.log(arrToReverse.reverse())
let arrToReverse1 = [1, 2, 3, 4];
let reversedArray = [];
arrToReverse1.forEach((ite) => {
reversedArray.unshift(ite);
})
console.log(reversedArray)
let arrToReverse2 = [1, 2, 3, 4];
for(let i=0; i<arrToReverse2.length/2; i++) {
[arrToReverse2[i], arrToReverse2[arrToReverse2.length-1-i]] = [arrToReverse2[arrToReverse2.length-1-i], arrToReverse2[i]]
}
console.log(arrToReverse2)
let nums = [1,2,3,5,5]
let sum = nums.reduce((acc, item, index, arr) => {
return acc+=item;
}, 0);
console.log(sum)
let arrayToFlat = [1,2,[3],[[4]],[[[5]]]]
function flatternArr (arrayToFlat) {
return arrayToFlat.reduce((acc, item) => {
return acc.concat(Array.isArray(item) ? flatternArr(item) : item);
}, [])
}
console.log(flatternArr(arrayToFlat))
let arrobj = [{name:'a',salary:20000,age:25},
{name:'b',salary:25000,age:23},
{name:'c',salary:34000,age:25},
{name:'d',salary:13000,age:30}]
console.log(arrobj.sort(
function (a,b) {
if (a.age===b.age) {
return (a.salary-b.salary)
}
return a.age-b.age
}
));
// CLOSURE
function greet(hi) {
return function (name) {
console.log(this) // window
console.log(name + hi)
}
}
greet('hi')('nishant')
const obj = {
a: this,
b: function(){
return this;
},
c: ()=>{
return this;
},
d(){
return this;
},
e: function(){
return this.a;
}
}
obj.a // window
obj.b() // obj
obj.c() // window
obj.d() // obj
obj.e() // window
function objectClone(obj) {
var clone = {}
for (var i in obj) {
if (typeof(obj[i]) == "object" && obj[i] != null) {
clone[i] = objectClone(obj[i]);
} else {
clone[i] = obj[i];
}
}
return clone;
}
// Half reverse the string:
// i/p: microsoft
// o/p: orcimtfos
let str = "microsoft";
function reversedString (str) {
let result = ""
for(let i=0; i<str.length; i++) {
let sliced = "";
if (i === (str.length-1)/2 || i== str.length-1) {
let end = i;
let start = i == str.length-1 ? end-(str.length-1)/2 : end-str.length/2;
while(end > start) {
sliced+=str[end]
end--;
}
}
result +=sliced;
}
return result;
}
console.log(reversedString(str))