Skip to content

Instantly share code, notes, and snippets.

@funador
Created August 2, 2018 16:14
Show Gist options
  • Save funador/dddeace439a23a1c008e6f36d2dc5734 to your computer and use it in GitHub Desktop.
Save funador/dddeace439a23a1c008e6f36d2dc5734 to your computer and use it in GitHub Desktop.
// filter
Array.prototype.myFilter = function(func) {
const arr = []
for (let i = 0; i < this.length; i++) {
const item = this[i]
if(func(item, i, this)) {
arr.push(item)
}
}
return arr
}
// map
Array.prototype.myMap = function(func) {
const arr = []
for (let i = 0; i < this.length; i++) {
arr.push(func(this[i], i , this))
}
return arr
}
// reduce
Array.prototype.myReduce = function(func, startValue) {
const arr = arguments.length === 1
? this
: [startValue, ...this]
let accumulator = arr[0]
for (let i = 1; i < arr.length; i++) {
accumulator = func(accumulator, arr[i], i, this)
}
return accumulator
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment