@rushiv/frecency
v2.0.0
Published
Frecency sorting for search results.
Downloads
56
Readme
Frecency
Frecency sorting for search results. Combines frequency and recency to rank results by how often and how recently they were selected.
Based on the original @mixmaxhq/frecency by Mixmax. This is a modernized fork that ships as ESM-only TypeScript with an updated toolchain.
ESM-only. This package ships ECMAScript modules only (no CommonJS). Requires Node >= 22.
Install
npm install @rushiv/frecencyUsage
Create a Frecency instance with a unique key. Frecency data is persisted in localStorage under frecency_<key>.
import Frecency from "@rushiv/frecency";
const peopleFrecency = new Frecency({
key: "people",
});When a user selects a search result, call save():
peopleFrecency.save({
searchQuery,
selectedId: selectedResult._id,
});Before displaying results, call sort() to rank them by frecency:
const sorted = peopleFrecency.sort({
searchQuery,
results: searchResults,
});sort() returns a new array ranked by frecency score. Pass keepScores: true if you need the scores (as _frecencyScore) for analytics or debugging:
const sorted = peopleFrecency.sort({
searchQuery,
results: searchResults,
keepScores: true,
});Configuration
idAttribute
Sorts on _id by default. Set a different attribute or a function:
const frecency = new Frecency({
key: "people",
idAttribute: "email",
});
// or a function for mixed result types
const frecency = new Frecency({
key: "people",
idAttribute: (result) => result.id || result.email,
});timestampsLimit
Number of selection timestamps to keep per result. More timestamps = more granular scoring but more storage used. Default: 10.
new Frecency({
key: "people",
timestampsLimit: 20,
});recentSelectionsLimit
Max number of unique IDs stored. More IDs = more results get frecency-ranked but more storage used. Default: 100.
new Frecency({
key: "people",
recentSelectionsLimit: 200,
});storageProvider
In the browser, frecency uses localStorage by default. In a Node.js (server) environment, a storage provider is required. Any object implementing the Web Storage API works, e.g. node-localstorage:
import { LocalStorage } from "node-localstorage";
const storageProvider = new LocalStorage(path.join(app.getPath("userData"), "frecency"));
new Frecency({
key: "people",
storageProvider,
});Async storage providers are also supported:
interface AsyncStorageProvider {
read: () => Promise<string | null>;
write: (value: string) => Promise<void> | void;
clear?: () => Promise<void> | void;
}Sync providers are re-read before every sort()/save() so multiple instances stay in sync. Async providers hydrate once at construction; save() mutates the local cache immediately and flushes in the background. Until the initial read() resolves, sort() returns unranked results. A save()/remove()/clear() that lands before hydration completes overwrites previously stored history (the cache wins).
If stored frecency data is corrupted or has an unexpected shape, it is ignored and tracking starts fresh (no throw).
Match weights
Three weights control how much each match type contributes to the final score:
| Option | Default | Description |
| --- | --- | --- |
| exactQueryMatchWeight | 1.0 | Result was previously selected for the exact same query |
| subQueryMatchWeight | 0.7 | Result was selected for a query that is a substring of the current query |
| recentSelectionsMatchWeight | 0.5 | Result was recently selected regardless of query |
Passing 0 disables a weight entirely (previously treated as "use default").
new Frecency({
key: "people",
exactQueryMatchWeight: 0.9,
subQueryMatchWeight: 0.5,
recentSelectionsMatchWeight: 0.1,
});decayBuckets
Custom recency decay buckets. Evaluated ascending by maxAgeMs; first bucket with age <= maxAgeMs wins. Default: 3h/100, 1d/80, 3d/60, 7d/30, 14d/10. The array must be non-empty with maxAgeMs > 0 and points > 0 on every entry, or the constructor throws.
new Frecency({
key: "people",
decayBuckets: [
{ maxAgeMs: 1000 * 60 * 60, points: 100 }, // 1 hour
{ maxAgeMs: 1000 * 60 * 60 * 24, points: 50 }, // 1 day
{ maxAgeMs: 1000 * 60 * 60 * 24 * 7, points: 10 }, // 1 week
],
});Methods
save({ searchQuery, selectedId })
Record a selection. Call this when a user picks a search result.
peopleFrecency.save({ searchQuery: "alice", selectedId: "user_123" });sort({ searchQuery, results, keepScores? })
Sort results by frecency. Returns a new array; never mutates the input results objects. Pass keepScores: true to get shallow copies with _frecencyScore attached.
const sorted = peopleFrecency.sort({ searchQuery: "alice", results: searchResults });remove(selectedId)
Remove a single ID from all frecency data (queries, selections, and recent selections).
peopleFrecency.remove("user_123");clear()
Reset all frecency data for this key, both in-memory and in storage.
peopleFrecency.clear();Credits
Original concept and implementation by Mixmax, based on Slack's frecency blog post. MIT licensed.
License
MIT
