allow to pass a getFn for a specific key

This commit is contained in:
Gabriel R. Abreu 2022-02-23 08:37:27 -03:00 committed by Kiro Risk
parent f5425ea1bd
commit 20668ecbe4
3 changed files with 30 additions and 2 deletions

View File

@ -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

View File

@ -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) {

View File

@ -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)
@ -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)