From 77f7c2ac11e1424aef9771e7a32271d1c1fafc07 Mon Sep 17 00:00:00 2001 From: Robin Bisping Date: Wed, 10 Jan 2024 14:57:59 +0100 Subject: [PATCH] feat: Add support for labeling functions --- index.js | 10 ++++++++-- test.js | 10 ++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index a01a82a..8475f3f 100644 --- a/index.js +++ b/index.js @@ -8,11 +8,16 @@ module.exports = prepareSimpleTextSearch // ``` // // Objects in a collection get stringified to search it. -// You can also define a property to search in: +// You can also define a property to search in or a pruning function to preprocess +// the collection: // ``` // var get = simpleTextSearch([{name: 'Zürich'}, {name: 'Marc'}], 'name') // var results = get('zurich') -// // -> returns [{name: 'Marc'}] +// // -> returns [{name: 'Zürich'}] +// +// var get = simpleTextSearch([{name: 'Zürich'}, {name: 'Marc'}], (v) => v.name) +// var results = get('zurich') +// // -> returns [{name: 'Zürich'}] // ``` function prepareSimpleTextSearch (collection, property) { let cachedPrunedElements @@ -22,6 +27,7 @@ function prepareSimpleTextSearch (collection, property) { for (const elem of collection) { let val = elem if (typeof property === 'string') val = val && val[property] + else if (typeof property === 'function') val = val && property(val) if (typeof val === 'object') val = JSON.stringify(val) else if (typeof val !== 'string') continue val = { pruned: clean(val), elem } diff --git a/test.js b/test.js index 01efbd2..dea2afe 100644 --- a/test.js +++ b/test.js @@ -77,3 +77,13 @@ assert.strictEqual(res7a[1], 'Test 1') const res7b = get7('2') assert.strictEqual(res7b.length, 1) assert.strictEqual(res7b[0], 'Hello 2') + +// Allows a specifying pruning function +const arr6 = [{ id: 1, name: 'Test' }, { id: 2, name: 'Marc' }] +const get10 = search(arr3, (option) => option.name) +const res10a = get3('Marc') +assert.strictEqual(res3a[0], arr3[1]) +assert.strictEqual(res3a.length, 1) + +const res10b = get3(2) +assert.strictEqual(res3b.length, 0)