Skip to content

Commit

Permalink
feat: Add support for labeling functions
Browse files Browse the repository at this point in the history
  • Loading branch information
robinbisping authored and marcbachmann committed Jan 10, 2024
1 parent 7949f7b commit 77f7c2a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
10 changes: 8 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 }
Expand Down
10 changes: 10 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 77f7c2a

Please sign in to comment.