Skip to content

Instantly share code, notes, and snippets.

@lucaong
Created August 11, 2021 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucaong/f556521b676d8ef6855755ddc17ab7a3 to your computer and use it in GitHub Desktop.
Save lucaong/f556521b676d8ef6855755ddc17ab7a3 to your computer and use it in GitHub Desktop.
Sketch of combiners for MiniSearch results of different searches
/**
* 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