before write the code of polyfill, we all should know what are polyfill. I know maximum persons doesn't know the word "Polyfill".
What is polyfill :-
I know you all can read the definition from other sources also. but let's see in 2 lines.
A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.
TU SMJHA
Koi nhi bro. I am there.
like see that old browsers that doesn't support newer functions like map, reduce, filter (es-6). so we will write code in that way tha every browser can support.
`
//here we will see the implementation of reduce.
//normal using inbuilt reduce function
//syntax
//arr.reduce(callback(accumulator, currentValue), initialValue)
const numbers = [1, 2, 3, 4, 5, 6];
function sum_reducer(accumulator, currentValue) {
return accumulator + currentValue;
}
let sum = numbers.reduce(sum_reducer);
console.log(sum);
let summation = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue
);
console.log(summation); // 21
`
In this example we are adding the values of array using reduce function. what if browser does not support reduce function. so that's why we will see our own simple implementation.
`
var OwnReduceFun = function(nums, fn, init) {
let ans = init;
for(let el of nums){
ans = fn(ans, el)
}
return ans
};
const numbers = [1, 2, 3, 4, 5, 6];
function sum_reducer(accumulator, currentValue) {
return accumulator + currentValue;
}
//call the function
let ans = OwnReduceFun(numbers, sum_reducer, 0)
console.log(ans) // 21
`
** We create function of reduce named OwnReduceFun that will take nums (Array) fn that is defined already, that will what we want to do and other is initial value**
Now i think all are understood
Top comments (0)