Skip to content
Merged
Show file tree
Hide file tree
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
12 changes: 8 additions & 4 deletions src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,14 @@ export class Query<T> {
return false
}

/**
* @note Predicate functions receive the actual value as-is,
* including arrays and objects, so check for them first.
*/
if (typeof selector === 'function') {
return selector(actualValue)
}

if (Array.isArray(actualValue)) {
return actualValue.every((value) => {
return compileCondition(selector)(value)
Expand All @@ -92,10 +100,6 @@ export class Query<T> {
return compileCondition(selector)(actualValue)
}

if (typeof selector === 'function') {
return selector(actualValue)
}

return actualValue === selector
})
}
Expand Down
19 changes: 19 additions & 0 deletions tests/query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,22 @@ it('combines predicates under an AND logic', () => {
.test({ id: 456, name: 'Kate' }),
).toBe(false)
})

it('supports a predicate function against an array property', () => {
const query = new Query<{ petNames: Array<string> }>().where({
petNames: (petNames) => petNames.includes('wolfy'),
})

expect(query.test({ petNames: ['wolfy'] })).toBe(true)
expect(query.test({ petNames: ['rex'] })).toBe(false)
expect(query.test({ petNames: [] })).toBe(false)
})

it('supports a condition against an array of objects', () => {
const query = new Query<{ posts: Array<{ title: string }> }>().where({
posts: { title: 'First' },
})

expect(query.test({ posts: [{ title: 'First' }] })).toBe(true)
expect(query.test({ posts: [{ title: 'Second' }] })).toBe(false)
})
Loading