實現一個鏈式調用的query方法

提供了一個數組結構的 data,要求實現一個 query 方法,返回一個新的數組,query 方法內部有 過濾、排序、分組
等操作,並且支持鏈式調用,調用最終的 execute 方法返回結果

你可以按照以下步驟實現這個 query 方法:

  • 定義一個數組結構的 data,例如:
const data = [
  { id: 1, name: 'Alice', age: 20, gender: 'female' },
  { id: 2, name: 'Bob', age: 25, gender: 'male' },
  { id: 3, name: 'Charlie', age: 30, gender: 'male' },
  { id: 4, name: 'David', age: 35, gender: 'male' },
  { id: 5, name: 'Ella', age: 40, gender: 'female' }
];
  • 定義一個 Query 類,該類包含一個 results 數組,以及一些操作方法,例如:
class Query {
  constructor(data) {
    this.results = data;
  }

  filter(callback) {
    this.results = this.results.filter(callback);
    return this;
  }

  sort(callback) {
    this.results = this.results.sort(callback);
    return this;
  }

  groupBy(key) {
    const groups = new Map();
    this.results.forEach((item) => {
      const group = item[key];
      if (groups.has(group)) {
        groups.get(group).push(item);
      } else {
        groups.set(group, [item]);
      }
    });
    this.results = groups;
    return this;
  }

  execute() {
    return this.results;
  }
}

在 Query 類的構造函數中初始化 results 數組爲傳入的數據數組 data。

定義 filter 方法,該方法接受一個回調函數作爲參數,過濾 results 數組中的元素,並將過濾後的結果存儲回 results 數組中,然後返回 this 對象以支持鏈式調用。

定義 sort 方法,該方法接受一個回調函數作爲參數,排序 results 數組中的元素,並將排序後的結果存儲回 results 數組中,然後返回 this 對象以支持鏈式調用。

定義 groupBy 方法,該方法接受一個字符串類型的參數 key,按照 key 對 results 數組中的元素進行分組,並將分組後的結果存儲回 results 數組中,然後返回 this 對象以支持鏈式調用。

定義 execute 方法,該方法返回經過操作後的 results 數組。

使用如下代碼調用 query 方法,實現過濾、排序、分組等操作:

const result = new Query(data)
  .filter((item) => item.age > 25)
  .sort((a, b) => a.age - b.age)
  .groupBy('gender')
  .execute();

console.log(result);

輸出結果爲:Map(2) {

 'female' => [
{ id: 5, name: 'Ella', age: 40, gender: 'female' } ],
'male' => [ { id: 3, name: 'Charlie', age: 30, gender: 'male' },
{ id: 4, name: 'David', age: 35, gender: 'male' }, { id: 2, name: 'Bob', age: 25, gender: 'male' } ]
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章