Skip to content

Commit

Permalink
allow to pass a getFn for a specific key
Browse files Browse the repository at this point in the history
  • Loading branch information
fakenickels authored and krisk committed May 3, 2022
1 parent f5425ea commit 20668ec
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
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: 'title', getFn: (book) => book.title },
{ name: 'authorName', getFn: (book) => book.author.firstName }
]
})
const result = fuse.search({ title: '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

0 comments on commit 20668ec

Please sign in to comment.