Skip to content

Instantly share code, notes, and snippets.

@sanskriti-dev
Created September 28, 2021 20:41
Show Gist options
  • Save sanskriti-dev/b762c41d0cfa20a7f5b2a935efbdb728 to your computer and use it in GitHub Desktop.
Save sanskriti-dev/b762c41d0cfa20a7f5b2a935efbdb728 to your computer and use it in GitHub Desktop.
Polyfills of Sum,Filter,Map,Reduce
let a2=[1,2,3,4]
//SUM
Array.prototype.sum2 = function () {
let sum = 0
for(let i = 0;i<this.length;i++)
{
sum+=this[i]
}
return sum
}
console.log(a2.sum2())
//FILTER
Array.prototype.filterArray = function(callback) {
let filterValue = []
for(var i = 0;i<this.length;i++)
{
if(callback(this[i]))
filterValue.push(this[i])
}
return filterValue
}
console.log(a2.filterArray(a => a>2))
//MAP
Array.prototype.myMap = function(callback) {
let filterValue = []
for(var i = 0;i<this.length;i++)
{
filterValue.push(callback(this[i]))
}
return filterValue
}
console.log(a2.myMap(a => a*2))
//REDUCE
Array.prototype.myReduce = function(callback,intialValue=0) {
let acc = intialValue
for(var i = 0;i<this.length;i++)
{
acc=callback(acc,this[i])
}
return acc
}
console.log(a2.myReduce((a,c) => a+c))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment