LRU cache, priority queue and trie
An LRU cache, a priority queue and a trie, each working on live input.
Apache-2.0Runs on this page
Package: @awacloud/fw
A memo in an LRU cache traced as you type the lookups, a priority queue drained in order, and prefix suggestions from a trie as you type.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
You need a bounded memo (thumbnails, parsed responses), a work queue where urgency is not arrival order, or instant autocompletion over a word list, all in memory and without a dependency.
Copy-paste steps
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. - Replace
WORDSwith your own keys;insert(key, value)accepts any value.
What it shows
lruCache.create({ maxSize, onEvict })as a memo:hasdecides hit or miss,getrefreshes recency,setstores a computed value, and the eviction callback shows that the least recently used key goes, not the oldest one.heap.create({ comparator, initial })as a priority queue;drain()returns the items in order (min-heap by the comparator).trie.create(),insertandsearch(prefix, limit)returning{ key, value }hits, Unicode-safe.- The three structures are independent instances: nothing is global.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { lruCache } from '@awacloud/fw/io/structures/lruCache.js';
import { heap } from '@awacloud/fw/io/structures/heap.js';
import { trie } from '@awacloud/fw/io/structures/trie.js';
fw.runtime.registerAllDeep([lruCache, heap, trie]);
const LRU = fw.runtime.resolve('lruCache');
const HEAP = fw.runtime.resolve('heap');
const TRIE = fw.runtime.resolve('trie');
/**
* Memoise an expensive lookup in a 3-entry LRU cache and record what happens.
* @param {string[]} keys the lookups, in order
* @returns {string[]} one line per hit, miss or eviction
*/
export function memoTrace(keys) {
const trace = [];
const cache = LRU.create({ maxSize: 3, onEvict: (/** @type {string} */ key) => trace.push(`evict ${key}`) });
for (const key of keys) {
if (cache.has(key)) {
cache.get(key); // a hit also makes the key the most recently used
trace.push(`hit ${key}`);
} else {
trace.push(`miss ${key}`); // the expensive work would run here
cache.set(key, key.toUpperCase());
}
}
return trace;
}
/**
* @param {{ name: string, priority: number }[]} tasks lower priority number = more urgent
* @returns {string[]} task names in the order a worker would take them
*/
export function drainOrder(tasks) {
const queue = HEAP.create({ comparator: (a, b) => a.priority - b.priority, initial: tasks });
return queue.drain().map((task) => task.name);
}
/** The words to complete: fw module names, as a docs search box would hold them. */
const WORDS = 'semaphore semver scheduler signal sha256 stats storage str trie tokenBucket'.split(' ');
const index = TRIE.create();
for (const word of WORDS) index.insert(word);
/** @param {string} prefix @param {number} [limit] @returns {string[]} matching words, at most `limit` */
export function suggest(prefix, limit = 5) {
return index.search(prefix, limit).map((hit) => hit.key);
}
/** @param {string} id @param {string[]} lines */
function showList(id, lines) {
/** @type {HTMLElement} */ (document.getElementById(id)).replaceChildren(...lines.map((line) => {
const li = document.createElement('li');
li.textContent = line;
return li;
}));
}
const lookups = /** @type {HTMLInputElement} */ (document.getElementById('lookups'));
const showTrace = () => showList('lru', memoTrace(lookups.value.split(',').map((k) => k.trim()).filter(Boolean)));
lookups.addEventListener('input', showTrace);
showTrace();
/** @type {HTMLElement} */ (document.getElementById('drain')).textContent = drainOrder([
{ name: 'backup', priority: 3 },
{ name: 'page the on-call', priority: 1 },
{ name: 'rotate logs', priority: 2 },
]).join(' → ');
const input = /** @type {HTMLInputElement} */ (document.getElementById('prefix'));
function update() {
const hits = input.value ? suggest(input.value) : [];
showList('suggestions', input.value && hits.length === 0 ? ['no match'] : hits);
}
input.addEventListener('input', update);
update();index.html
<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fw · LRU cache, priority queue and trie</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>LRU cache, priority queue and trie</h1>
<h2>A memo in an LRU cache of 3 entries</h2>
<label for="lookups">Lookups, in order (comma-separated)</label>
<input id="lookups" type="text" value="a, b, c, a, d, b" autocomplete="off">
<ol id="lru" aria-label="Cache trace" aria-live="polite"></ol>
<h2>Priority queue</h2>
<p>Drained in priority order: <output id="drain"></output></p>
<h2>Trie suggestions</h2>
<label for="prefix">Type a module name</label>
<input id="prefix" type="search" value="s" autocomplete="off">
<ul id="suggestions" aria-live="polite"></ul>
</main>
</body>
</html>