From f1293668106dd27539ae64c62c3d7a7ada92fb04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Tue, 11 Mar 2025 16:30:04 +0100 Subject: [PATCH] theme: Add a simple LRU cache for search --- assets/js/alpinejs/data/search.js | 12 +++++++++++- assets/js/helpers/index.js | 1 + assets/js/helpers/lrucache.js | 19 +++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 assets/js/helpers/lrucache.js diff --git a/assets/js/alpinejs/data/search.js b/assets/js/alpinejs/data/search.js index e5ebf81a0..c633799a1 100644 --- a/assets/js/alpinejs/data/search.js +++ b/assets/js/alpinejs/data/search.js @@ -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: { diff --git a/assets/js/helpers/index.js b/assets/js/helpers/index.js index b02d81cf0..41ffa3c39 100644 --- a/assets/js/helpers/index.js +++ b/assets/js/helpers/index.js @@ -1,2 +1,3 @@ export * from './bridgeTurboAndAlpine'; export * from './helpers'; +export * from './lrucache'; diff --git a/assets/js/helpers/lrucache.js b/assets/js/helpers/lrucache.js new file mode 100644 index 000000000..258848c95 --- /dev/null +++ b/assets/js/helpers/lrucache.js @@ -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); + } +}