theme: Add a simple LRU cache for search

This commit is contained in:
Bjørn Erik Pedersen 2025-03-11 16:30:04 +01:00
parent 339ca33883
commit f129366810
3 changed files with 31 additions and 1 deletions

View File

@ -1,3 +1,5 @@
import { LRUCache } from '../../helpers';
const designMode = false;
const groupByLvl0 = (array) => {
@ -36,7 +38,7 @@ export const search = (Alpine, cfg) => ({
query: designMode ? 'apac' : '',
open: designMode,
result: {},
cache: new LRUCache(10), // Small cache, avoids network requests on e.g. backspace.
init() {
Alpine.bind(this.$root, this.root);
@ -66,6 +68,13 @@ export const search = (Alpine, cfg) => ({
this.result = {};
return;
}
// Check cache first.
const cached = this.cache.get(this.query);
if (cached) {
this.result = cached;
return;
}
var queries = {
requests: [
{
@ -91,6 +100,7 @@ export const search = (Alpine, cfg) => ({
.then((response) => response.json())
.then((data) => {
this.result = groupByLvl0(applyHelperFuncs(data.results[0].hits));
this.cache.put(this.query, this.result);
});
},
root: {

View File

@ -1,2 +1,3 @@
export * from './bridgeTurboAndAlpine';
export * from './helpers';
export * from './lrucache';

View File

@ -0,0 +1,19 @@
// A simple LRU cache implementation backed by a map.
export class LRUCache {
constructor(maxSize) {
this.maxSize = maxSize;
this.cache = new Map();
}
get(key) {
return this.cache.get(key);
}
put(key, value) {
if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, value);
}
}