[underscore 源碼學習] 數(shù)組定位 與 平攤數(shù)組

數(shù)組定位

  • _.initial
    _.initial(array, n):獲取 array 除了最后 n 個元素以外的元素航背。
// 源碼
_.initial = function(array, n, guard) {
  return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)))
}
  • _.rest = _.tail = _.drop
    _rest(array, n):返回 array 中除了前 n 個元素外的所有元素律秃。
// 源碼
_.rest = function(array, n, guard) {
  return slice.call(array, n == null || guard ? 1 : n);
};

攤平數(shù)組

  • _.flatten
    _.flatten(array, shadow):攤平 array,通過 shadow 指明是深度攤平還是淺攤平顶捷。
  • flatten 接收兩個參數(shù)
    1. array: 待攤平數(shù)組
    2. shallow:是否是淺攤平,反之為深度攤平屎篱。

下面我們開始源碼學習:

test.js

(function(root) {

    const toString = Object.prototype.toString;
    const push = Array.prototype.push;

    const _ = function(obj) {

        if (obj instanceof _) {
            return obj;
        }

        if (!(this instanceof _)) {
            return new _(obj);
        }
        this._wrapped = obj;
    };

    const flatten = function(array, shallow) {
        const ret = [];
        let index = 0;
        for (let i = 0; i < array.length; i++) {
            let value = array[i];
            if (_.isArray(value)) {
                // 遞歸全部展開
                if (!shallow) {
                    value = flatten(value, shallow);
                }
                let j = 0;
                let len = value.length;
                while (j < len) {
                    ret[index++] = value[j++];
                }
            } else {
                ret[index++] = value;
            }
        }
        return ret;
    };

    _.flatten = function(array, shallow) {
      return flatten(array, shallow);
    };

    _.initial = function(array, n) {
        return [].slice.call(array, 0, Math.max(0, array.length - (n == null ? 1 : n)));
    };

    _.rest = function(array, n, guard) {
        return [].slice.call(array, n == null ? 1 : n);
    };

    // 以上 --------------------------------

    // 返回一個 [min, max] 區(qū)間內的任意整數(shù)
    _.random = function(min, max) {
        if (max == null) {
            max = min;
            min = 0;
        }
        // 這里 + 1 的原因是因為 Math.random() 的值永遠 (0,1) ; 大于 0 小于 1 服赎。
        // 假設 min 為 3,max 為 6交播;所以是 min + x重虑;x 要想取到 3,則必須 + 1秦士。(0.99 * 4 = 3.96缺厉,向下取整為 3)。
        return min + Math.floor((Math.random() * (max - min + 1)));
    };

    _.clone = function(obj) {
        return _.isArray(obj)? obj.slice() : Object.assign({}, obj);
    };

    _.sample = function(array, n) {
        if (n == null) {
            return array[_.random(array.length - 1)]
        }
        const sample = _.clone(array);
        const length = sample.length;
        const last = length - 1;
        n = Math.max(Math.min(n, length), 0);
        for (let index = 0; index < n; index++) {
            // 抽取 [index, last] 中某一位
            // 例如這里隨機取 [0, 10] 中的 5隧土,交換 sample[0] 和 sample[5] 的值提针。下一次迭代取 [1, 10] 之間的值。所以不會重復的值
            const rand = _.random(index, last);
            const temp = sample[index];
            sample[index] = sample[rand]; // 交換
            sample[rand] = temp;
        }
        return sample.slice(0, n);
    };

    // ---------------------

    const createPredicateIndexFinder = function(dir) {
        return function (array, predicate, context) {
            predicate = cb(predicate, context);
            const length = array.length;
            let index = dir > 0? 0 : length - 1;
            for (index; index >= 0 && index < length; index += dir) {
                if (predicate(array[index], index, array)) {
                    return index;
                }
            }
            return -1;
        };
    };

    _.findIndex = createPredicateIndexFinder(1);
    _.findLastIndex = createPredicateIndexFinder(-1);

    _.sortedIndex = function(array, obj, iteratee, context) {
        iteratee = cb(iteratee, context, 1);
        const value = iteratee(obj);
        let low = 0;
        let high = array.length;
        while(low < high) {
            let mid = Math.floor((low + high) / 2);
            if (iteratee(array[mid]) < value) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
    };

    _.isBoolean = function(obj) {
        return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
    };

    // 判斷數(shù)據(jù)類型為 NaN
    _.isNaN = function(obj) {
        return _.isNumber(obj) && isNaN(obj);
    };

    const createIndexFinder = function(dir, predicateFind, sortedIndex) {
        return function(array, item, idx) {
            let i = 0;
            let length = array.length;
            // idx 布爾值代表是否是已經排序好的數(shù)組
            if (sortedIndex && _.isBoolean(idx) && length) {
                // 滿足條件則使用二分查找
                idx = sortedIndex(array, item);
                return array[idx] === item ? idx : -1;
            }

            // 特殊情況 如果要查找的元素是 NaN 類型 NaN !== NaN
            if (item != item) {
                idx = predicateFind(slice.call(array, i, length), _.isNaN);
                return idx >= 0 ? idx + i : -1;
            }

            // 非上述情況正常遍歷
            for (idx = dir > 0? i : length -1; idx >=0 && idx < length; idx += dir) {
                if (array[idx] === item) return idx;
            }

            return -1;
        };
    };

    _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
    _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);


    _.filter = function(obj, predicate, context) {
        predicate = cb(predicate, context);

        const results = [];

        _.each(obj, function(value, index, list) {
            if (predicate(value, index, list)) {
                results.push(value);
            }
        });

        return results;
    };

    // (direction)dir 為 1曹傀,從左到右累加辐脖;dir 為 -1,從右到左累加皆愉。
    const createReduce = function(dir) {

        const reducer = function(obj, iteratee, memo, initial) {
            const keys = !_.isArray(obj) && Object.keys(obj);
            const length = (keys || obj).length;
            let index = dir > 0? 0 : length - 1;

            // 如果不包含初始值嗜价,則使用 第一個或最后一個值 作為初始化值,并相應移動 index dir 步幕庐。
            if (!initial) {
                memo = obj[keys? keys[index] : index];
                index += dir;
            }

            for (index; index >= 0 && index < length; index += dir) {
                const currentKey = keys? keys[index] : index;
                memo = iteratee(memo, obj[currentKey], currentKey, obj);
            }
            return memo;
        };


        return function(obj, iteratee, memo, context) {
            // 如果值的個數(shù)大于等于 3久锥,說明存在初始化值
            const initial = arguments.length >= 3;
            return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
        };
    };

    _.reduce = createReduce(1);

    _.reduceRight = createReduce(-1);

    // rest 參數(shù)
    _.restArguments = function(func) {
        // rest 參數(shù)位置
        const startIndex = func.length - 1;
        return function() {
            const length = arguments.length - startIndex;
            const rest = Array(length);
            // rest 數(shù)組中的成員
            for (let index = 0; index < length; index++) {
                rest[index] = arguments[index + startIndex];
            }
            // 非 rest 參數(shù)成員的值一一對應
            const args = Array(startIndex + 1);
            for (let index = 0; index < startIndex; index++) {
                args[index] = arguments[index];
            }

            args[startIndex] = rest;
            return func.apply(this, args);
        };
    };


    _.isFunction = function(obj) {
        return typeof obj === 'function';
    };

    const cb = function(iteratee, context, count) {
        if (iteratee === void 0) {
            return _.identity;
        }

        if (_.isFunction(iteratee)) {
            return optimizeCb(iteratee, context, count);
        }
    };

    const optimizeCb = function(func, context, count) {
        if (context === void 0) {
            return func;
        }

        switch (count == null ? 3 : count) {
            case 1:
                return function(value) {
                    return func.call(context, value);
                };
            case 3:
                return function(value, index, obj) {
                    return func.call(context, value, index, obj);
                };
            case 4:
                return function(memo, value, index, obj) {
                    return func.call(context, memo, value, index, obj);
                }
        }
    };

    _.identity = function(value) {
        return value;
    };

    _.map = function(obj, iteratee, context) {
        // 生成不同功能迭代器
        const cbIteratee = cb(iteratee, context);
        const keys = !_.isArray(obj) && Object.keys(obj);
        const length = (keys || obj).length;
        const result = Array(length);

        for (let index = 0; index < length; index++) {
            const currentKey = keys? keys[index] : index;
            result[index] = cbIteratee(obj[currentKey], index, obj);
        }

        return result;
    };

    _.unique = function(obj, callback) {
        const res = [];
        for (let i = 0; i < obj.length; i++) {
            const val = callback? callback(obj[i]) : obj[i];
            if (res.indexOf(val) === -1) {
                res.push(val);
            }
        }
        return res;
    };

    _.isArray = function(obj) {
        return toString.call(obj) === "[object Array]";
    };

    _.functions = function(obj) {
        const res = [];
        for (let key in obj) {
            res.push(key);
        }
        return res;
    };

    _.each = _.forEach = function(obj, iteratee, context) {
        iteratee = optimizeCb(iteratee, context);
        if (_.isArray(obj)) {
            for (let i = 0;i < obj.length; i++) {
                iteratee(obj[i], i, obj);
            }
        } else {
            for (let key in obj) {
               iteratee(obj[key], key, obj);
            }
        }
        return obj;
    };

    _.chain = function(obj) {
        const instance = _(obj);
        instance._chain = true;
        return instance;
    };

    const result = function(instance, obj) {
        return instance._chain? _(obj).chain() : obj;
    };

    _.prototype.value = function() {
        return this._wrapped;
    };

    _.mixin = function(obj) {
        _.each(_.functions(obj), (name) => {
            const func = obj[name];

            _.prototype[name] = function() {
                let args = [this._wrapped];
                push.apply(args, arguments);
                return result(this, func.apply(this, args));
            };
        });
    };

    _.mixin(_);

    root._ = _;
})(this);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>underscore</title>
</head>
<body>
    <script src="./test.js"></script>
    <script>
        console.log(_.flatten([1, [2,3], [4, [5]]], true));
        console.log(_.initial([1,2,3,4,5], 2));
        console.log(_.rest([1,2,3,4,5], 2));
    </script>
</body>
</html>

顯示結果如下:


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市异剥,隨后出現(xiàn)的幾起案子瑟由,更是在濱河造成了極大的恐慌,老刑警劉巖冤寿,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件歹苦,死亡現(xiàn)場離奇詭異绿鸣,居然都是意外死亡,警方通過查閱死者的電腦和手機暂氯,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門潮模,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人痴施,你說我怎么就攤上這事擎厢。” “怎么了辣吃?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵动遭,是天一觀的道長。 經常有香客問我神得,道長厘惦,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任哩簿,我火速辦了婚禮宵蕉,結果婚禮上,老公的妹妹穿的比我還像新娘节榜。我一直安慰自己羡玛,他們只是感情好,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布宗苍。 她就那樣靜靜地躺著稼稿,像睡著了一般。 火紅的嫁衣襯著肌膚如雪讳窟。 梳的紋絲不亂的頭發(fā)上让歼,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天,我揣著相機與錄音丽啡,去河邊找鬼谋右。 笑死,一個胖子當著我的面吹牛碌上,可吹牛的內容都是我干的倚评。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼馏予,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了盔性?” 一聲冷哼從身側響起霞丧,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎冕香,沒想到半個月后蛹尝,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體后豫,經...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年突那,在試婚紗的時候發(fā)現(xiàn)自己被綠了挫酿。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡愕难,死狀恐怖早龟,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情猫缭,我是刑警寧澤葱弟,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站猜丹,受9級特大地震影響芝加,放射性物質發(fā)生泄漏。R本人自食惡果不足惜射窒,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一藏杖、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧脉顿,春花似錦制市、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至汉柒,卻和暖如春误褪,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背碾褂。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工兽间, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人正塌。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓嘀略,卻偏偏與公主長得像,于是被迫代替她去往敵國和親乓诽。 傳聞我的和親對象是個殘疾皇子帜羊,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內容