Refactor: allow filterpipe to specify key

This commit is contained in:
shamoon
2024-09-13 21:10:17 -07:00
parent 8e555cce9e
commit fb3a881387
3 changed files with 40 additions and 14 deletions

View File

@@ -25,4 +25,25 @@ describe('FilterPipe', () => {
itemsReturned = pipe.transform(items, null)
expect(itemsReturned).toEqual(items)
})
it('should filter matchingmodel items by key', () => {
const pipe = new FilterPipe()
const items: MatchingModel[] = [
{
id: 1,
name: 'Hello World',
slug: 'slug-1',
},
{
id: 2,
name: 'Hello with slug',
slug: 'not this',
},
]
let itemsReturned = pipe.transform(items, 'slug')
expect(itemsReturned).toEqual(items)
itemsReturned = pipe.transform(items, 'slug', 'slug')
expect(itemsReturned).toEqual([items[0]])
})
})

View File

@@ -5,21 +5,26 @@ import { MatchingModel } from '../data/matching-model'
name: 'filter',
})
export class FilterPipe implements PipeTransform {
transform(items: MatchingModel[], searchText: string): MatchingModel[] {
transform(
items: MatchingModel[],
searchText: string,
key?: string
): MatchingModel[] {
if (!items) return []
if (!searchText) return items
return items.filter((item) => {
return Object.keys(item)
.filter(
(key) =>
typeof item[key] === 'string' || typeof item[key] === 'number'
)
.some((key) => {
return String(item[key])
.toLowerCase()
.includes(searchText.toLowerCase())
})
const keys = key
? [key]
: Object.keys(item).filter(
(key) =>
typeof item[key] === 'string' || typeof item[key] === 'number'
)
return keys.some((key) => {
return String(item[key])
.toLowerCase()
.includes(searchText.toLowerCase())
})
})
}
}