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
The second line in myReduce is redundant. You could just put
var accumulator = initialVal;
or used initialVal in for loop instead of accumulator, it would do the same.I would change it to the following implementation:
Other than that - great job of putting it together!
PS If you change file extension to .js you'll have awesome syntax highlighting ;)