Polyfill
o/p js question:
https://www.youtube.com/playlist?list=PLQOMi2yb4hF2kQ5Axv_tdznWLInV5qj8M
forEach
let arr = [1,2,3,4]
arr.forEach((ele)=> console.log(ele)) //1,2,3,4
Array.prototype.myForEach= function(cb){
//console.log(this) // [1,2,3,4]
for(i=0;i<this.length;i++){
cb(this[i])
}
}
arr.myForEach((ele)=> console.log(ele)) //1,2,3,4
Map
let arr = [1,2,3,4]
const modifyArr = arr.map((ele,arr,i)=> ele*2)
console.log(modifyArr) // [2,4,6,8]
// map polyfill
Array.prototype.myMap= function(cb){
let arr =[]
for(i=0;i<this.length;i++){
arr.push(cb(this[i],this,i))
}
return arr
}
const modifyMyArr = arr.myMap((ele,arr,i)=> ele*2)
console.log(modifyMyArr) // [2,4,6,8]
Filter
let arr = [1,2,3,4]
const modifyArr = arr.filter((ele,arr,i)=> ele%2===0)
console.log(modifyArr) // [ 2, 4 ]
// filter polyfill
Array.prototype.myFilter= function(cb){
let arr =[]
for(i=0;i<this.length;i++){
if(cb(this[i],this,i)) arr.push(this[i])
}
return arr
}
const modifyMyArr = arr.myFilter((ele,arr,i)=> ele%2===0)
console.log(modifyMyArr) // [ 2, 4 ]
Reduce
let arr = [1,2,3,4]
const sum = arr.reduce((acc,curr,i,arr)=> {
return acc+curr
},0)
console.log(sum)
// Reduce polyfill
Array.prototype.myReduce= function(cb, init){
let acc=init
for(i=0;i<this.length;i++){
acc = acc ? cb(acc,this[i],this,i) : this[i]
}
return acc
}
const sum1 = arr.myReduce((acc,curr,arr,i)=>{
return acc+curr
},0)
console.log(sum1)
const person1 ={
name: 'gokul'
}
const person2={
name:'karthik'
}
function details(age,place){
return `my name is ${this.name} and age is ${age}, lives in ${place}`
}
Call
details.call(person1,26,'Mumbai') //my name is gokul and age is 26,lives in Mumbai
details.call(person2,17,'Bombay') //my name is karthik and age is 17,lives in Bombay
// call polyfill
Function.prototype.myCall = function(obj={}, ...args){
//console.log(this) // [Function: details]
if(typeof this !== "function"){
throw new Error('cant be called')
}
//console.log(obj) //{name: 'gokul'}
//console.log(args) //[26,'Mumbai']
obj.fn = this
//console.log(obj) //{name: 'gokul',fn:[Function: details]}
obj.fn(...args)
}
details.myCall(person1,26,'Mumbai')
Apply
details.apply(person1,[26,'Mumbai']) //my name is gokul and age is 26,lives in Mumbai
details.apply(person2,[17,'Bombay']) //my name is karthik and age is 17,lives in Bombay
// apply polyfill
Function.prototype.myApply = function(obj={}, ...args){
//console.log(this) // [Function: details]
if(typeof this !== "function"){
throw new Error('cant be called')
}
if(!Array.isArray(...args)){
throw new Error('TypeError: cant be called')
}
//console.log(obj) //{name: 'gokul'}
//console.log(args) //[26,'Mumbai']
obj.fn = this
//console.log(obj) //{name: 'gokul',fn:[Function: details]}
obj.fn(...args)
}
details.myApply(person1,[26,'Mumbai'])
Bind
const newFn = details.bind(person1)
newFn(26,'Mumbai') //my name is gokul and age is 26,lives in Mumbai
const newFn2 = details.bind(person2)
newFn2(17,'Bombay') //my name is karthik and age is 17,lives in Bombay
// bind polyfill
Function.prototype.myBind = function(obj={}, ...args1){
//console.log(this) // [Function: details]
if(typeof this !== "function"){
throw new Error('cant be called')
}
//console.log(obj) //{name: 'gokul'}
//console.log(args1) //[26]
obj.fn = this
//console.log(obj) //{name: 'gokul',fn:[Function: details]}
return function(...args2){
//console.log(args2) //['Mumbai']
obj.fn(...args1,...args2)
}
}
const newFn3 = details.myBind(person1,26)
newFn3('Mumbai') //my name is gokul and age is 26,lives in Mumbai
Array flat method
let arr =[1,2,3,[4,5]]
consloe.log(arr.flat(1)) // [1,2,3,4,5]
let arr2 =[1,2,3,[[4,5]]]
consloe.log(arr2.flat(2)) // [1,2,3,4,5]
Array.prototype.myFlat = function(depth){
// console.log(this) //[1,2,3,[4,5]]
let res =[]
if(!Array.isArray(this)){
throw new Error(`${this}.flat is not a fn`)
}
this.forEach((ele)=>{
if(Array.isArray(ele) && depth>0){
res.push(...ele.myFlat(depth-1))
}else{
res.push(ele)
}
})
return res
}
let arr2 =[1,2,3,[[4,5]]]
consloe.log(arr2.myFlat(2)) // [1,2,3,4,5]
Debounce -->setTimeout()-->cb(),clearTimeout()
const myDebounce =(cb,delay)=>{
let timer
return function(...args){
if(timer) clearTimeout(timer)
timer=setTimeout(()=> cb(...args),delay)
}
}
Throttle -->setTimeout()-->(false)
function myThrottle(cb, delay = 250) {
let shouldWait = false
return (...args) => {
if (!shouldWait) {
cb(...args)
shouldWait = true
setTimeout(() => shouldWait = false, delay)
}
}
}
Promise.all() --> all promise are resolved in same order as provided , if any one promise fail the all promise are rejected
const promise1 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("promise1")
},1000)
})
const promise2 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("promise2")
},100)
})
// maintain the order , (promise2 is resolved first), if it is resolved it return array of resolved promised in order
Promise.all([promise1,promise2]).then(console.log).catch(console.log)
// ['promise1','promise2']
const myPromiseAll = (arrayPromise) => {
if (!Array.isArray(arrayPromise) || arrayPromise.length === 0) {
throw new Error('Input must be a non-empty array.');
}
let res = [];
return new Promise((resolve, reject) => {
arrayPromise.forEach((promise, index) => {
promise
.then((data) => {
res[index] = data; // for maintaining the order of resolved promises
if (index === arrayPromise.length - 1) {
// all promises are fulfilled, then only it should resolve
resolve(res);
}
})
.catch((error) => reject(error));
});
});
};
myPromiseAll([promise1, promise2])
.then(console.log)
.catch(console.log);
// Output: ['promise1', 'promise2']
Promise.any() --> any promise which is first fulfilled or all promise rejected (array of rejected promise)
const promise1 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("promise1")
},1000)
})
const promise2 = new Promise((resolve,reject)=>{
resolve("promise2")
})
const promise3 = 3
Promise.any([promise1,promise2,promise3]).then((res)=>conslole.log(res)).catch((error)=>console.log(error))
// promise2
const myPromiseAny = (arrayPromise) => {
if (!Array.isArray(arrayPromise)) {
throw new Error('Input must be an array.');
}
let errors = [];
let counter = 0;
return new Promise((resolve, reject) => {
arrayPromise.forEach((promise, index) => {
promise
.then((data) => resolve(data))
.catch((error) => {
counter++;
errors[index] = error;
if (counter === arrayPromise.length) reject(errors);
});
});
});
};
myPromiseAny([promise1, promise2, promise3])
.then((res) => console.log(res))
.catch((error) => console.log(error));
Promise.race()
const myPromiseRace = (arrayPromise) => {
if (!Array.isArray(arrayPromise)) {
throw new Error('Input must be an array.');
}
return new Promise((resolve, reject) => {
arrayPromise.forEach((promise) => {
Promise.resolve(promise)
.then((data) => resolve(data))
.catch((error) => reject(error));
});
});
};
myPromiseRace([promise1, promise2, promise3])
.then((res) => console.log(res))
.catch((error) => console.log(error));
Promise.allSettled()
const myPromiseAllSettled = (arrayPromise) => {
if (!Array.isArray(arrayPromise)) {
throw new Error('Input must be an array.');
}
return new Promise((resolve) => {
const settledPromises = [];
let settledCount = 0;
arrayPromise.forEach((promise, index) => {
Promise.resolve(promise)
.then((value) => {
settledPromises[index] = { status: 'fulfilled', value };
settledCount++;
if (settledCount === arrayPromise.length) {
resolve(settledPromises);
}
})
.catch((reason) => {
settledPromises[index] = { status: 'rejected', reason };
settledCount++;
if (settledCount === arrayPromise.length) {
resolve(settledPromises);
}
});
});
});
};
// Usage
const promise1 = new Promise((resolve) => setTimeout(resolve, 1000, 'foo'));
const promise2 = new Promise((_, reject) => setTimeout(reject, 500, 'bar'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 1500, 'baz'));
myPromiseAllSettled([promise1, promise2, promise3])
.then((results) => console.log(results))
.catch((error) => console.error(error));