Created
September 28, 2021 20:41
-
-
Save sanskriti-dev/b762c41d0cfa20a7f5b2a935efbdb728 to your computer and use it in GitHub Desktop.
Polyfills of Sum,Filter,Map,Reduce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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