Skip to content

Commit

Permalink
feat: added support for strength based fuzzy searching
Browse files Browse the repository at this point in the history
  • Loading branch information
cecilia-sanare committed Jun 27, 2024
1 parent 4e1eaf8 commit 134d6e8
Showing 1 changed file with 29 additions and 5 deletions.
34 changes: 29 additions & 5 deletions src/workers/search.worker.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
import { getApps } from '@/service/protontweaks';
import { delay } from '@ribbon-studios/js-utils';

// listen for main to transfer the buffer to myWorker
self.onmessage = async (event) => {
const [filteredApps] = await Promise.all([
getApps().then((apps) => apps.filter((app) => app.name.toLowerCase().includes(event.data.toLowerCase()))),
delay(500),
]);
const [filteredApps] = await Promise.all([filterApps(event.data.toLowerCase()), delay(500)]);

self.postMessage(filteredApps);
};

async function filterApps(value: string) {
// TODO: Add a method of getting an api version (git sha) and using it to enable caching and cache busting
const apps = await getApps();

const partials = value.split(' ').filter(Boolean);

return apps
.filter((app) => {
return partials.some((partial) => app.name.toLowerCase().includes(partial));
})
.map((app) => ({
...app,
strength: determineMatchStrength(value, partials, app.name.toLowerCase()),
}))
.sort((a, b) => b.strength - a.strength);
}

function determineMatchStrength(value: string, partials: string[], comparisonValue: string): number {
if (comparisonValue === value) return 100;
const matches = partials
// Filter out the non matches
.filter((partial) => comparisonValue.includes(partial))
// Calculate the number of characters that matched
.reduce((output, partial) => output + partial.length, 0);

return Math.floor((matches / value.length) * 100);
}

0 comments on commit 134d6e8

Please sign in to comment.