Skip to content

Instantly share code, notes, and snippets.

  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
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.
//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;
};
@dmytsv
Copy link

dmytsv commented May 12, 2019

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:

Array.prototype.myReduce = function(cb, reducer) {
    const {length} = this;
    let i = 0;
    if (!reducer) {
        reducer = this[0];
        i++;
    }
    for (; i < length; i++) {
        reducer = cb(reducer, this[i], i, this)
    }
    return reducer;
}

Other than that - great job of putting it together!

PS If you change file extension to .js you'll have awesome syntax highlighting ;)

@Tellisense
Copy link
Author

thanks Dmitry!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment