关于链式调用,核心是只需要在每一步的操作最后返回 this 即可。
代码主要关注点在于return this;,并且该query函数返回的是各个函数的对象{where, sortBy……}
代码示例:
function query(list) {
let currentList = list;
function where(condition) {
currentList = currentList.filter(condition);
return this;
}
function sortBy(key) {
currentList = currentList.sort((a, b) => (a[key] < b[key] ? -1 : 1));
return this;
}
function groupBy(key) {
const groups = {};
currentList.forEach(item => {
if (!groups[item[key]]) {
groups[item[key]] = [];
}
groups[item[key]].push(item);
});
currentList = Object.values(groups);
return this;
}
function execute() {
return currentList;
}
return {
where,
sortBy,
groupBy,
execute,
};
}
使用示例:
const data = [
{ id: 1, name: 'Alice', age: 15 },
{ id: 2, name: 'Bob', age: 20 },
{ id: 3, name: 'Charlie', age: 25 },
{ id: 4, name: 'Alice', age: 30 },
];
const result = query(data)
.where(item => item.age > 18) // 过滤出 age 大于 18 的项
.sortBy('id') // 按 id 排序
.groupBy('name') // 按 name 分组
.execute(); // 执行查询并返回结果
console.log(result); // 输出结果:[ [ { id: 3, name: 'Charlie', age: 25 }, { id: 4, name: 'Alice', age: 30 } ] ]