Add .filter/.filterBy methods
This commit is contained in:
parent
6627ed4732
commit
dda859805e
2 changed files with 30 additions and 0 deletions
10
index.js
10
index.js
|
@ -10,6 +10,16 @@ module.exports = class Query {
|
||||||
return this.data;
|
return this.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
filter (func) {
|
||||||
|
this.data = this.data.filter(func);
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
|
filterBy (key, func) {
|
||||||
|
this.data = this.data.filter(item => func(item[key]));
|
||||||
|
return this;
|
||||||
|
};
|
||||||
|
|
||||||
search (key, term, score = 0) {
|
search (key, term, score = 0) {
|
||||||
switch (typeof term) {
|
switch (typeof term) {
|
||||||
case 'boolean':
|
case 'boolean':
|
||||||
|
|
|
@ -66,6 +66,26 @@ test('should sort by string name', () => {
|
||||||
expect(query[0].name).toBe('Dudley Conner');
|
expect(query[0].name).toBe('Dudley Conner');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('should filter', () => {
|
||||||
|
let isAgeOver33 = a => a.age > 33;
|
||||||
|
|
||||||
|
let query = new Query(TestData)
|
||||||
|
.filter(isAgeOver33)
|
||||||
|
.results;
|
||||||
|
|
||||||
|
expect(query[0].name).toBe('Howard Buckley');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should filter by key', () => {
|
||||||
|
let isNumGT33 = num => num > 33;
|
||||||
|
|
||||||
|
let query = new Query(TestData)
|
||||||
|
.filterBy('age', isNumGT33)
|
||||||
|
.results;
|
||||||
|
|
||||||
|
expect(query[0].name).toBe('Howard Buckley');
|
||||||
|
});
|
||||||
|
|
||||||
test('should chain everything together', () => {
|
test('should chain everything together', () => {
|
||||||
let query = new Query(TestData)
|
let query = new Query(TestData)
|
||||||
.search('isActive', true)
|
.search('isActive', true)
|
||||||
|
|
Loading…
Add table
Reference in a new issue