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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more