From 23f00bc483b2d572427933aaac950998dcf56acd Mon Sep 17 00:00:00 2001 From: Yami <38581557+ymssx@users.noreply.github.com> Date: Fri, 7 Aug 2020 15:57:20 +0800 Subject: [PATCH] feat: base --- src/query.ts | 56 +++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 45 insertions(+), 11 deletions(-) diff --git a/src/query.ts b/src/query.ts index e107598..4a8a65d 100644 --- a/src/query.ts +++ b/src/query.ts @@ -1,11 +1,16 @@ +import * as _ from 'lodash'; import { Data, Field } from './types'; export class Query { private data; + private dataGroup; + private fileds; constructor(data: Data) { this.data = data; + this.dataGroup = { data }; + this.fileds = []; } /** @@ -13,8 +18,10 @@ export class Query { * @param fields */ public select(...fields: Field[]): Query { - - // TODO + this.fileds = [ + ...this.fileds, + ...fields, + ]; return this; } @@ -25,8 +32,14 @@ export class Query { * @param asc */ public orderBy(fields: string, asc?: boolean): Query { - - // TODO + for (const fileds in this.dataGroup) { + if (typeof this.dataGroup[fields][0][fields] === 'number') { + this.dataGroup[fields].sort((item1, item2) => asc ? item1 > item2 : item1 < item2); + } else { + this.dataGroup[fields].sort(); + } + } + return this; } @@ -37,8 +50,15 @@ export class Query { * @param fields */ public groupBy(fields: string): Query { + const tempMap = {}; + this.data.forEach(item => { + if (!tempMap[item[fields]]) { + tempMap[item[fields]] = []; + } + tempMap[item[fields]].push(item); + }) - // TODO + this.dataGroup = tempMap; return this; } @@ -48,8 +68,10 @@ export class Query { * @param n */ public limit(n: number): Query { - - // TODO + for (const fileds in this.dataGroup) { + const groupData = this.dataGroup[fileds]; + this.dataGroup[fileds] = groupData.slice(0, n); + } return this; } @@ -58,9 +80,21 @@ export class Query { * 返回最后的查询数据 */ public record(): Data { + const res = []; + for (const group of this.dataGroup.values()) { + const groupData = group.reduce((data, item) => { + const itemData = {}; + for (const key in item) { + if (this.fileds.includes(key)) { + itemData[key] = item[key]; + } + } + data.push(itemData); + return data; + }, []); + res.push(groupData); + } - // TODO - - return []; + return res; } -} \ No newline at end of file +}