From 20668ecbe4e63c701edfaee83f61d13e107e868f Mon Sep 17 00:00:00 2001 From: "Gabriel R. Abreu" Date: Wed, 23 Feb 2022 08:37:27 -0300 Subject: [PATCH] allow to pass a getFn for a specific key --- src/tools/FuseIndex.js | 2 +- src/tools/KeyStore.js | 2 +- test/indexing.test.js | 28 ++++++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/tools/FuseIndex.js b/src/tools/FuseIndex.js index 6473424..4fe4b5c 100644 --- a/src/tools/FuseIndex.js +++ b/src/tools/FuseIndex.js @@ -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 diff --git a/src/tools/KeyStore.js b/src/tools/KeyStore.js index 40ed421..7c96477 100644 --- a/src/tools/KeyStore.js +++ b/src/tools/KeyStore.js @@ -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) { diff --git a/test/indexing.test.js b/test/indexing.test.js index 9c5d431..6b74cf1 100644 --- a/test/indexing.test.js +++ b/test/indexing.test.js @@ -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)