Skip to content
This repository has been archived by the owner on Aug 13, 2020. It is now read-only.

feat: base #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 45 additions & 11 deletions src/query.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
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 = [];
}

/**
* 选择字段
* @param fields
*/
public select(...fields: Field[]): Query {

// TODO
this.fileds = [
...this.fileds,
...fields,
];

return this;
}
Expand All @@ -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;
}
Expand All @@ -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;
}
Expand All @@ -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;
}
Expand All @@ -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;
}
}
}