Initial commit
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* 解析 Pro 方法的匹配器参数
|
||||
* @param {(Function|string|*)} a - 回调函数、属性键、或单值
|
||||
* @param {*=} b - 属性值(与 a 配合使用)
|
||||
* @returns {function(*): boolean} 匹配函数
|
||||
* @private
|
||||
*/
|
||||
const _resolveMatcher = (a, b) => {
|
||||
if (typeof a === 'function') return a;
|
||||
if (typeof a === 'string' && b !== undefined) return (item) => item != null && item.getPro(a) === b;
|
||||
return (item) => item === a;
|
||||
};
|
||||
|
||||
/** @private @type {string[]} 支持增强方法的原始方法列表 */
|
||||
const _methods = ['find', 'filter', 'findIndex', 'findLast', 'some', 'every'];
|
||||
|
||||
_methods.forEach((method) => {
|
||||
/**
|
||||
* 增强版数组遍历方法,支持三种调用模式
|
||||
*
|
||||
* **模式1 - 回调函数**(同原生方法)
|
||||
* @example
|
||||
* arr.findPro(item => item.id > 1)
|
||||
* arr.filterPro(item => item.active)
|
||||
*
|
||||
* **模式2 - 单值精确匹配**
|
||||
* @example
|
||||
* ['aa','bb','cc'].findPro('bb')
|
||||
* [1,2,2,3].filterPro(2)
|
||||
*
|
||||
* **模式3 - key-value 匹配**(支持嵌套路径,通过 getPro 访问)
|
||||
* @example
|
||||
* [{ user: { name: 'Bob' } }].findPro('user.name', 'Bob')
|
||||
* arr.filterPro('status', 1)
|
||||
*
|
||||
* @name ${method}Pro
|
||||
* @memberof Array.prototype
|
||||
* @method
|
||||
* @param {(Function|string|*)} a - 回调函数、属性键、或单值
|
||||
* @param {*=} [b] - 属性值(当 a 为 string 时使用)
|
||||
* @returns {*} 返回结果同对应原生方法
|
||||
*/
|
||||
Array.prototype[`${method}Pro`] = function (a, b) {
|
||||
return this[method](_resolveMatcher(a, b));
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user