What is a polyfill?
A polyfill is a piece of code (or plugin) that provides the technology that we, the developers, expect the browser to provide natively.
On a simpler term, you can till of A polyfill as a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers, e.g., to support canvas (an HTML5 feature) in older browsers.
Let's start
let's write a polyfill for map()
original syntax of the map function
let newArray = arr.map(callback(currentValue, index, array) {
// return element for newArray, after executing something
});
Polyfill for Map()
Array.prototype.myMap = function (callBack) {
let newArray = [];
for (let i = 0; i < this.length; i++) {
newArray = [...newArray, callBack(this[i], i, this)];
}
return newArray;
};
let's write a polyfill for Filter()
original syntax of the filter function
let newArray = arr.filter(callback(currentValue, index, array) {
// return element for newArray, if true
});
Polyfill for filter()
Array.prototype.myFilter = function (callBack) {
let newArray = [];
for (let i = 0; i < this.length; i++) {
newArray = callBack(this[i], i, this) ? [...newArray, this[i]] : newArray;
}
return newArray;
};
let's write a polyfill for reduce()
original syntax of the reduce function
arr.reduce(callback( accumulator, currentValue, index, array ), initialValue)
Polyfill for reduce ()
Array.prototype.myReduce = function (callback, initialValue) {
let accumulator = initialValue;
for (let i = 0; i < this.length; i++) {
if (accumulator != undefined) {
accumulator = callback(accumulator, this[i], i, this);
} else {
accumulator = this[i];
}
}
return accumulator;
};
let's write a polyfill for find()
original syntax of the find function
array.find(function(currentValue, index, arr),thisValue)
Polyfill for find()
Array.prototype.myFind = function(callBack) {
for (var i = 0; i < length; i++) {
value = list[i];
if (callBack( value, i, list)) {
return value;
}
}
return undefined;
};
let's write a polyfill for bind()
original syntax of the bind function
let newFunction = currentFunction.bind(newThisValue)
Polyfill for Bind()
Function.prototype.mybind = function (context, ...args1) {
let fn = this;
return function (...arg2) {
fn.apply(context, [...args1, ...arg2])
}
};
Conclusion
Since now we have written pollyfills for map(),filter(),reduce(),find() and bind() I hope you have better understanding of these functions now