Last active
July 7, 2022 00:40
-
-
Save Tellisense/ba0641d74fc04a37c41dfbd74e718298 to your computer and use it in GitHub Desktop.
Creating our own advanced Array methods: forEach, map, filter, reduce, every and some, using native javascript code, so that we can understand them better.
This file contains hidden or 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
//forEach | |
Array.prototype.myforEach = function(cb) { | |
for (let i = 0; i < this.length; i++){ | |
cb(this[i], i, this); | |
} | |
return undefined; | |
}; | |
//map | |
Array.prototype.myMap = function(cb) { | |
let newArr = []; | |
for (let i = 0; i < this.length; i++){ | |
newArr.push(cb(this[i], i, this)); | |
} | |
return newArr; | |
}; | |
//filter | |
Array.prototype.myFilter = function(cb) { | |
let newArr = []; | |
for (let i = 0; i < this.length; i++) { | |
if (cb(this[i], i, this)){ | |
newArr.push(this[i]); | |
} | |
} | |
return newArr; | |
}; | |
//some | |
Array.prototype.mySome = function(cb) { | |
for (let i = 0; i < this.length; i++) { | |
if (cb(this[i], i, this)){ | |
return true; | |
} | |
}; | |
return false; | |
}; | |
//every | |
Array.prototype.myEvery = function(cb) { | |
for (let i = 0; i < this.length; i++) { | |
if (!cb(this[i], i, this)){ | |
return false; | |
} | |
}; | |
return true; | |
}; | |
//reduce | |
Array.prototype.myReduce = function(cb, initialVal) { | |
var accumulator = (initialVal === undefined) ? undefined : initialVal; | |
for (var i = 0; i < this.length; i++) { | |
if (accumulator !== undefined){ | |
accumulator = cb.call(undefined, accumulator, this[i], i, this); | |
} else { | |
accumulator = this[i]; | |
} | |
} | |
return accumulator; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks Dmitry!