Skip to content

Commit 77f7c2a

Browse files
robinbispingmarcbachmann
authored andcommitted
feat: Add support for labeling functions
1 parent 7949f7b commit 77f7c2a

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

index.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,16 @@ module.exports = prepareSimpleTextSearch
88
// ```
99
//
1010
// Objects in a collection get stringified to search it.
11-
// You can also define a property to search in:
11+
// You can also define a property to search in or a pruning function to preprocess
12+
// the collection:
1213
// ```
1314
// var get = simpleTextSearch([{name: 'Zürich'}, {name: 'Marc'}], 'name')
1415
// var results = get('zurich')
15-
// // -> returns [{name: 'Marc'}]
16+
// // -> returns [{name: 'Zürich'}]
17+
//
18+
// var get = simpleTextSearch([{name: 'Zürich'}, {name: 'Marc'}], (v) => v.name)
19+
// var results = get('zurich')
20+
// // -> returns [{name: 'Zürich'}]
1621
// ```
1722
function prepareSimpleTextSearch (collection, property) {
1823
let cachedPrunedElements
@@ -22,6 +27,7 @@ function prepareSimpleTextSearch (collection, property) {
2227
for (const elem of collection) {
2328
let val = elem
2429
if (typeof property === 'string') val = val && val[property]
30+
else if (typeof property === 'function') val = val && property(val)
2531
if (typeof val === 'object') val = JSON.stringify(val)
2632
else if (typeof val !== 'string') continue
2733
val = { pruned: clean(val), elem }

test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,13 @@ assert.strictEqual(res7a[1], 'Test 1')
7777
const res7b = get7('2')
7878
assert.strictEqual(res7b.length, 1)
7979
assert.strictEqual(res7b[0], 'Hello 2')
80+
81+
// Allows a specifying pruning function
82+
const arr6 = [{ id: 1, name: 'Test' }, { id: 2, name: 'Marc' }]
83+
const get10 = search(arr3, (option) => option.name)
84+
const res10a = get3('Marc')
85+
assert.strictEqual(res3a[0], arr3[1])
86+
assert.strictEqual(res3a.length, 1)
87+
88+
const res10b = get3(2)
89+
assert.strictEqual(res3b.length, 0)

0 commit comments

Comments
 (0)