indexOf & lastIndexOf
-
underscore中通過內(nèi)置的工廠函數(shù)createIndexFinder來創(chuàng)建一個索引查詢器。 -
_.indexOf及_.lastIndexOf正是該函數(shù)所創(chuàng)建的。
createIndexFinder(dir, predicateFind, sortedIndex) 接收 3 個參數(shù)
-
dir查詢方向,_.indexOf是正向查詢,_.lastIndexOf是反向查詢。 -
predicateFind真值檢測函數(shù),該函數(shù)只能在查詢元素不是數(shù)字時(NaN)才會使用。 -
sortedIndex有序數(shù)組的索引獲得函數(shù)。如果設置了該參數(shù),將假定數(shù)組已經(jīng)有序,從而更加高效地通過針對有序數(shù)組的查詢函數(shù)(比如二分查找等)來優(yōu)化查詢性能。
_.indexOf
- _.indexOf(array, item, sorted):查詢
item在array中第一次出現(xiàn)的位置。
// 源碼
_.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
_.indexOf 方法的創(chuàng)建過程中,被傳遞了 _.findIndex 作為元素的真值預測函數(shù),以及 _.sortedIndex 作為當數(shù)組有序時獲取索引的方式。
_.lastIndexOf
- _.lastIndexOf(array, item, sorted):查詢 item 在 array 中最后一次出現(xiàn)的位置
// 源碼
_.lastIndexOf = createIndexFinder(-1, _findLastIndex);
下面我們開始源碼實現(xiàn):
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 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);
console.log(iteratee);
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 布爾值代表是否是已經(jīng)排序好的數(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(_.indexOf([1,2,3,4,5,6,7,8,9], 3, true));
console.log(_.lastIndexOf([1,2,3,4,5,6,7,8,9], 6));
</script>
</body>
</html>
結(jié)果顯示如下:
