Here are five important polyfills in javascript. I will be covering
forEach
,map
,filter
,reduce
,flat
in the easiest way possible.
NOTE : Knowledge of the This
keyword is crucial.
Let's get started!
forEach
The code below is a simple example of forEach
.
const numbers = [1, 2, 3, 4, 5] const ans = numbers.forEach((n) => console.log(n))
polyfill of forEach
const numbers = [1, 2, 3, 4, 5] Array.prototype.myForEach = function (callbackfn) { for (let index = 0; index < this.length; index++) { callbackfn(this[index], index, this) } } numbers.myForEach((n) => console.log(n))
map
Simple example of in-built map
function
const numbers = [1, 2, 3, 4, 5] console.log(numbers.map((n) => n * 2));
Here is polyfill of map
const numbers = [1, 2, 3, 4, 5] Array.prototype.myMap = function myMap(cb) { const output = [] for (let i = 0; i < this.length; i++) { let a = cb(this[i]) output.push(a) } return output } console.log(numbers.myMap((n) => n * 2));
filter
Here is filter
example
const numbers = [1, 2, 3, 4, 5] console.log(numbers.filter((n) => n > 3));
Polyfill of filter
const numbers = [1, 2, 3, 4, 5] Array.prototype.myFilter = function (cb) { const output = [] for (let i = 0; i < this.length; i++) { if (cb(this[i])) { output.push(this[i]) } } return output } console.log(numbers.myFilter((n) => n > 4));
reduce
example of reduce
method
const numbers = [1, 2, 3, 4, 5] console.log(numbers.reduce((acc, curr) => { return acc + curr }, 0) );
polyfill of reduce
const numbers = [1, 2, 3, 4, 5] Array.prototype.myReduce = function (cb, initialValue) { let acc = initialValue; for (let i = 0; i < this.length; i++) { acc = acc ? cb(acc, this[i]) : this[i] } return acc } console.log(numbers.myReduce((acc, curr) => { return acc + curr }, 1));
flat
Example of flat
method, it takes depth as an argument. Depth refers to how deeply nested arrays within the original array should be flattened.
const numbers = [1, [2, [3, 4]]] console.log(numbers.flat(2));
polyfill of flat
const numbers = [1, [2, [3, 4]]] Array.prototype.myflat = function (depth) { const output = [] if (!Array.isArray(this)) { throw new Error(`${this}.flat is not a function`); } this.forEach((n) => { if (Array.isArray(n) && depth > 0) { output.push(...n.myflat(depth - 1)) } else { output.push(n) } }); return output } console.log(numbers.myflat(2));
Top comments (0)