Fulfilling all function arguments in order before invoking

前端 未结 3 471
清歌不尽
清歌不尽 2020-12-21 23:34

I\'m trying to understand how the following zip function (esp. the invoke function) can be made more functional. The issue I\'ve got is that the invoke method has to wait fo

3条回答
  •  独厮守ぢ
    2020-12-22 00:14

    I don't see why do you want to make your code more functional. Nevertheless I did improve upon your zip function by removing the invoke function entirely. You really don't need it:

    function zip(a, b, callback) {
        var left = [], right = [];
    
        a.forEach(function (value) {
            if (right.length)
                callback([value, right.shift()]);
            else left.push(value);
        });
    
        b.forEach(function (value) {
            if (left.length)
                callback([left.shift(), value]);
            else right.push(value);
        });
    }
    

    See the output for yourself: http://jsfiddle.net/Tw6K2/

    The code is more imperative than functional. However I doubt it gets any better than this.

提交回复
热议问题