Created
August 11, 2021 10:06
-
-
Save lucaong/f556521b676d8ef6855755ddc17ab7a3 to your computer and use it in GitHub Desktop.
Sketch of combiners for MiniSearch results of different searches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Usage: | |
* | |
* import { and, or } from 'minisearch-combiner' | |
* | |
* and(resultsA, resultsB) | |
* | |
* or(resultsA, resultsB) | |
* | |
* and(or(resultsA, resultsB), resultsC) | |
* | |
*/ | |
const or = (a, b) => { | |
return sortByScore(Object.values(a.concat(b).reduce((byId, result) => { | |
if (byId[result.id] == null) { | |
byId[result.id] = { | |
...result, | |
match: { ...result.match } | |
} | |
} else { | |
byId[result.id].score += result.score | |
Object.assign(byId[result.id].match, result.match) | |
} | |
return byId | |
}, {}))) | |
} | |
const and = (a, b) => { | |
const aById = a.reduce((byId, result) => { | |
byId[result.id] = result | |
return byId | |
}, {}) | |
return sortByScore(b.reduce((results, result) => { | |
const other = aById[result.id] | |
if (other != null) { | |
results.push({ | |
...result, | |
score: result.score + other.score, | |
match: { ...result.match, ...other.match } | |
}) | |
} | |
return results | |
}, [])) | |
} | |
const sortByScore = (results) => | |
results.sort(({ score: a }, { score: b }) => a < b ? 1 : -1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment