DEV Community

Pawan Poojary
Pawan Poojary

Posted on

Javascript most asked polyfills

ForEach Polyfill:

Array.prototype.forEachPoly = function(cb){

    for(let i = 0; i < this.length; i++){
        cb(this[i], i, this);
    }
}
Enter fullscreen mode Exit fullscreen mode

Map Polyfill:

Array.prototype.mapPoly = function(cb){
    let newArr = [];
    for(let i=0; i<this.length; i++){
        newArr.push(cb(this[i], i, this));
    }
    return newArr;
}
Enter fullscreen mode Exit fullscreen mode

Filter Polyfill:

Array.prototype.filterPoly = function(cb){
    let newArr = [];
    for(let i=0; i<this.length; i++){
        if(cb(this[i], i, this)){
            newArr.push(this[i]);
        }
    }
    return newArr;
}
Enter fullscreen mode Exit fullscreen mode

Reduce Polyfill:

Array.prototype.reducePoly = function(cb, optionalInitilizer){
    console.log(optionalInitilizer);
    let acc, i;
    if(optionalInitilizer !== undefined){
        acc = optionalInitilizer;
        i=0
    }else{
        acc = this[0];
        i=1;
    }

    for(i; i<this.length; i++){
        acc = cb(acc, this[i],i,this)
    }
    return acc;
}
Enter fullscreen mode Exit fullscreen mode

OR

Array.prototype.reducePoly2 = function(cb, initializer){
    let acc = initializer;
    for(let i=0; i<this.length; i++){
        acc = acc ? cb(acc, this[i], i, this) : this[0];
    }
    return acc;
}
Enter fullscreen mode Exit fullscreen mode

Call Polyfill:

Function.prototype.callPoly = function(context={}, ...args){
    context.func = this;
    context.func(...args);
}
Enter fullscreen mode Exit fullscreen mode

Apply Polyfill:

Function.prototype.applyPoly = function(context={}, args){
    context.func = this;
    context.func(...args);
}
Enter fullscreen mode Exit fullscreen mode

Bind Polyfill:

Function.prototype.bindPoly = function(context={}, ...args){
    let reqFunc = this;
    return function(...newArgs){
        context.func = reqFunc;
        context.func(...args, ...newArgs);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)