Partial built-in iteration of js arrays using for grammar simulation

Keywords: Javascript Programming

It's been almost two years since the beginning of the front-end business. It's a shame that the famous Professional JavaScript for Web Developers has only recently begun. Of course, for all of you, the Chinese translation of the book "JavaScript Advanced Programming" is just like a thunderbolt. Two years is not a short time. With the support of Baidu and other technology bloggers, we have a lot of knowledge reserve of JavaScript, but these knowledge are too many, complex and unsystematic. Reading this time is like filing a lot of fragmentary knowledge in the brain.
Privately, the best way to test learning outcomes is to retell them in your own way. For programmers, batch data manipulation is a very important skill, JavaScript arrays provide us with many built-in methods, so that we can easily batch data manipulation. Today's whim: How do you implement those iteration methods in arrays with JS? For JS engines, these methods may have more efficient implementations, but for me, it seems that they can only be implemented through traversal.

1. Array.prototype.reverse

The reverse method is used to reverse the order of arrays. For the time being, it can only be realized by traversing and exchanging:

    Array.prototype.fakeReverse = function fakeReverse(){
        var len = this.length - 1;
        var halfLen = len / 2;
        if(!len){
            return this
        } else {
            for(var index = 0; index <= halfLen; index++){
                var item = this[index];
                this[index] = this[len - index];
                this[len - index] = item;
            }
        }
        
        return this;
    } 

2. Array.prototype.filter

As the name implies, filter is used to filter out eligible array elements and return a new array. The idea is to create a new array to store all tested elements:

    Array.prototype.fakeFilter = function fakeFilter(callback){
        if(!(callback instanceof Function)){
            throw new Error(`Uncaught TypeError: ${callback} is not a function`)
        }
        var res = [];
        for(var index = 0; index < this.length; index++){
            if(!!callback(this[index], index, this)){
                res.push(this.index);
            }
        }
        
        return res;
    }

3. Array.prototype.map

The map method returns a new array that maps the elements of the current array. The idea is also to create new arrays to store all mapped elements:

    Array.prototype.fakeMap = function fakeMap(callback){
        if(!(callback instanceof Function)){
            throw new Error(`Uncaught TypeError: ${callback} is not a function`)
        }
        var res = [];
        for(var index = 0; index < this.length; index++){
            res.push(callback(this[index], index, this));
        }
        
        return res;
    }

4. Array.prototype.reduce

The reduce method accepts two parameters: the first parameter is a callback function, and the second parameter is an "initial value". The callback function is traversed to process the initial value and the current array element. The returned value will be the "initial value" of the next processing:

    Array.prototype.fakeReduce = function fakeReduce(callback, initVal){
        if(!(callback instanceof Function)){
            throw new Error(`Uncaught TypeError: ${callback} is not a function`)
        }
        
        let curVal = initVal;
        
        for(var index = 0; index < this.length; index++){
            initVal = callback(initVal, this[index], index, this);
        }
        
        return initVal;
    }

5. Array.prototype.forEach

The forEach method is used to traverse each element in an array:

    Array.prototype.fakeEach = function fakeEach(callback){
        if(!(callback instanceof Function)){
            throw new Error(`Uncaught TypeError: ${callback} is not a function`)
        }
        
        for(var index = 0; index < this.length; index++){
            callback(this[index], index, this);
        }
    }

There are only a few array methods in this paper. We originally wanted to implement Array.prototype.sort, but there are so many sorting methods and many optimization techniques. So we intend to do some research first, and then write a special article on array sorting method when we have time. The above codes may not be used in practical projects, but the customized sorting method may be useful, because choosing the right sorting algorithm for different scenarios can effectively improve the efficiency of the program.

Posted by steonkeys on Wed, 28 Aug 2019 08:07:28 -0700