Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow to pass a getFn for a specific key #627

Merged
merged 2 commits into from
May 3, 2022
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
2 changes: 1 addition & 1 deletion src/tools/FuseIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export default class FuseIndex {
// Iterate over every key (i.e, path), and fetch the value at that key
this.keys.forEach((key, keyIndex) => {
// console.log(key)
let value = this.getFn(doc, key.path)
let value = key.getFn ? key.getFn(doc) : this.getFn(doc, key.path)

if (!isDefined(value)) {
return
Expand Down
2 changes: 1 addition & 1 deletion src/tools/KeyStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function createKey(key) {
id = createKeyId(name)
}

return { path, id, weight, src }
return { path, id, weight, src, getFn: key.getFn }
}

export function createKeyPath(key) {
Expand Down
28 changes: 28 additions & 0 deletions test/indexing.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ describe('Searching', () => {
expect(myIndex.keys).toBeDefined()
})

test('createIndex: ensure keys can be created with getFn', () => {
let myIndex = Fuse.createIndex(
[
{ name: 'title', getFn: (book) => book.title },
{ name: 'author.firstName', getFn: (book) => book.author.firstName }
],
Books
)
expect(myIndex.records).toBeDefined()
expect(myIndex.keys).toBeDefined()
})

test('parseIndex: ensure index can be exported and Fuse can be initialized', () => {
const myIndex = Fuse.createIndex(options.keys, Books)
expect(myIndex.size()).toBe(Books.length)
Expand All @@ -46,6 +58,22 @@ describe('Searching', () => {
expect(idx(result)).toMatchObject([0])
})

test('parseIndex: search with getFn', () => {
const fuse = new Fuse(Books, {
useExtendedSearch: true,
includeMatches: true,
includeScore: true,
threshold: 0.3,
keys: [
{ name: 'bookTitle', getFn: (book) => book.title },
{ name: 'authorName', getFn: (book) => book.author.firstName }
]
})
const result = fuse.search({ bookTitle: 'old man' })
expect(result.length).toBe(1)
expect(idx(result)).toMatchObject([0])
})

test('Fuse can be instantiated with an index', () => {
let myIndex = Fuse.createIndex(options.keys, Books)
const fuse = new Fuse(Books, options, myIndex)
Expand Down