实现一个 query 方法,实现对数据的链式查询和处理

要求
query 传入参数为原始数据(数组格式,每个元素都是对象)
通过进行链式调用对数据执行操作,支持的方法有where(predicate): 根据参数的条件进行筛选,参数与 [].filter 的参数类似
orderBy(key, desc): 根据 key 的值进行排列,默认升序排列,当第二个参数为 true 时降序排列
groupBy(key): 根据 key 的值对数据元素进行分组,合并为二维数组
execute(): 执行所有处理并返回最终结果
执行 execute 方法时才真正执行操作并返回结果
请结合下面示例理解需求
示例
const data = [
{ name: ‘foo’, age: 16, city: ‘shanghai’ },
{ name: ‘bar’, age: 24, city: ‘hangzhou’ },
{ name: ‘fiz’, age: 22, city: ‘shanghai’ },
{ name: ‘baz’, age: 19, city: ‘hangzhou’ }
];

query(data)
.where(item => item.age > 18)
.orderBy(‘age’)
.groupBy(‘city’)
.execute();

// 结果返回
[
[
{ name: ‘baz’, age: 19, city: ‘hangzhou’ },
{ name: ‘bar’, age: 24, city: ‘hangzhou’ },
],
[
{ name: ‘fiz’, age: 22, city: ‘shanghai’ },
]
]

直接上代码
function query(arr){
  function myArray(){}
  let myProto = myArray.prototype;
  if(Object.prototype.toString.call(arr).slice(8,-1)!==='Array') {
  	return console.error('must be an array')
  }
  myArray.prototype.where = function(){
  	 list = list.filter(cb);
     return { ...myProto };
  }
   myArray.prototype.orderBy = function (key) {
          list = list.sort((a, b) => a[key] - b[key]);
          return { ...myProto };
        };
        myArray.prototype.groupBy = function (key) {
          let ls = [];
          let group = list.reduce((pre, item) => {
            pre[item[key]] = [...(pre[item[key]] || []), item];
            return pre;
          }, {});
          list = [];
          for (let key in group) {
            list.push(group[key]);
          }
          return { ...myProto };
        };
        myArray.prototype.execute = function (key) {
          return list;
        };
        return { ...myProto };
}
   let res = query(data)
        .where((item) => item.age > 18)
        .orderBy("age")
        .groupBy("city")
        .execute();
      console.log(res);

你可能感兴趣的:(前端)