From dadee965e5afa288d2b6759e11172271442e0cbd Mon Sep 17 00:00:00 2001 From: Joeri Exelmans Date: Sun, 11 May 2025 09:30:48 +0200 Subject: [PATCH] trie: add get function --- lib/util/trie.js | 13 +++++++++++++ tests/trie.js | 14 +++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/util/trie.js b/lib/util/trie.js index 3c70968..b156e96 100644 --- a/lib/util/trie.js +++ b/lib/util/trie.js @@ -160,6 +160,19 @@ export const suggest = trie => key => maxSuggestions => { return __suggest(trie, "", key, maxSuggestions); } +export const get = trie => key => { + if (key === '') { + return trie.value; + } + const [pos] = binarySearch(trie.children, key); + if (pos < trie.children.length) { + const [haveKey, haveChildNode] = trie.children[pos]; + if (key.startsWith(haveKey)) { + return get(haveChildNode)(key.slice(haveKey.length)); + } + } +} + const __suggest = (trie, path, remaining, maxSuggestions) => { if (maxSuggestions === 0) { return []; diff --git a/tests/trie.js b/tests/trie.js index 215c371..116158b 100644 --- a/tests/trie.js +++ b/tests/trie.js @@ -3,7 +3,9 @@ import * as assert from "node:assert"; import { module2Env } from "../lib/environment/env.js"; import { ModuleStd } from "../lib/stdlib.js"; import { pretty } from "../lib/util/pretty.js"; -import { emptyTrie, growPrefix, insert, isProperlySorted, suggest } from "../lib/util/trie.js"; +import { emptyTrie, get, growPrefix, insert, isProperlySorted, suggest } from "../lib/util/trie.js"; +import { push } from "../lib/structures/list.js"; +import { getInst } from "../lib/primitives/dynamic.js"; /////////////////// @@ -104,4 +106,14 @@ assert.deepEqual( assert.deepEqual( suggest(bigTrie)("df")(2), [] +); + +assert.equal( + getInst(get(bigTrie)("list.push")), + push +); + +assert.equal( + get(bigTrie)("ooo"), + undefined ); \ No newline at end of file