mirror of
https://github.com/gohugoio/hugoDocs.git
synced 2025-09-08 16:44:41 -04:00
theme: Add a simple LRU cache for search
This commit is contained in:
parent
339ca33883
commit
f129366810
@ -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: {
|
||||
|
@ -1,2 +1,3 @@
|
||||
export * from './bridgeTurboAndAlpine';
|
||||
export * from './helpers';
|
||||
export * from './lrucache';
|
||||
|
19
assets/js/helpers/lrucache.js
Normal file
19
assets/js/helpers/lrucache.js
Normal 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);
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user