题目:提供了一个数组结构的 data,要求实现一个 query 方法,返回一个新的数组,query 方法内部有 过滤、排序、分组 等操作,并且支持链式调用,调用最终的 execute 方法返回结果:
// js
// const result = query(list)
// .where(item => item.age > 18)
// .sortBy('id')
// .groupBy('name')
// .execute();
// console.log(result);
const listPro = [
{
name: '章三',
id: 5,
age: 20
},
{
name: '章五',
id: 2,
age: 14
},
{
name: '章三',
id: 8,
age: 14
},
{
name: '章三',
id: 1,
age: 22
},
{
name: '章五',
id: 3,
age: 19
}
]
解题思路一:构造函数:
function Fun1 (data){
this.data = data
// this.where = function(cd){
// this.data = this.data.filter(cd)
// return this
// }
}
Fun1.prototype.where = function(cd){
this.data = this.data.filter(cd)
return this
}
Fun1.prototype.sortBy = function(key){
this.data = this.data.sort((a,b)=>a[key]-b[key])
return this
}
Fun1.prototype.groupBy = function(key){
const map = new Map();
this.data.forEach((d) => {
if (map.has(d[key])) {
map.get(d[key]).push(d);
} else {
map.set(d[key], [d]);
}
});
this.data = Array.from(map.values());
return this;
}
Fun1.prototype.execute = function(){
return this.data
}
function query (listPro){
return new Fun1(listPro)
}
const result = query(listPro)
.where(item => item.age > 18)
.sortBy('id')
.groupBy('name')
.execute();
console.log(result);
解题思路二:class
class fun1 {
constructor(data){
this.data = data
}
where(fun) {
this.data = this.data.filter(fun)
return this
}
sortBy(key){
// for(let i=0; i<this.data.length-1; i++){
// //每一轮比较要比多少次
// for(let j=0; j<this.data.length-1-i; j++){
// //如果第一个比第二个大,就交换他们两个位置
// if(this.data[j][key]<this.data[j+1][key]){
// var temp = this.data[j];
// this.data[j] =this.data[j+1];
// this.data[j+1] = temp;
// }
// }
// }
this.data = this.data.sort((a,b)=>a[key]-b[key])
return this
}
groupBy(key){
const map = new Map();
this.data.forEach((d) => {
if (map.has(d[key])) {
map.get(d[key]).push(d);
} else {
map.set(d[key], [d]);
}
});
this.data = Array.from(map.values());
return this;
}
execute(){
console.log(this.data)
return this
}
}
function query (listPro){
return new fun1(listPro)
}
const result = query(listPro)
.where(item => item.age > 18)
.sortBy('id')
.groupBy('name')
.execute();
console.log(result);