Skip to content

Instantly share code, notes, and snippets.

@gabrielrufino
Last active August 21, 2020 22:06
Show Gist options
  • Save gabrielrufino/e41b1161c54cd36c4c6a130ea8346ac6 to your computer and use it in GitHub Desktop.
Save gabrielrufino/e41b1161c54cd36c4c6a130ea8346ac6 to your computer and use it in GitHub Desktop.
My implementation of Map, Filter and Reduce <3
Array.prototype.map = function (callback) {
const result = []
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this))
}
return result
}
Array.prototype.filter = function (callback) {
const result = []
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
result.push(this[i])
}
}
return result
}
Array.prototype.reduce = function (callback, initial = 0) {
let accumulator = initial
for (let i = 0; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this)
}
return accumulator
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment