dope2/tests/trie.js

132 lines
No EOL
3 KiB
JavaScript

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, get, growPrefix, insert, isProperlySorted, suggest } from "../lib/util/trie.js";
import { push } from "../lib/structures/list.js";
import { getInst } from "../lib/primitives/dynamic.js";
///////////////////
// Setup TRIE 1 ...
const with1Item = insert(emptyTrie)('abba')('dancing queen');
console.log(pretty(with1Item));
const with2Items = insert(with1Item)('aboriginal')('australia');
console.log(pretty(with2Items));
const with3Items = insert(with2Items)('food')('pizza');
console.log(pretty(with3Items));
const with4Items = insert(with3Items)('absent')('not here');
console.log(pretty(with4Items));
const with5Items = insert(with4Items)('000')('000');
console.log(pretty(with5Items));
const with6Items = insert(with5Items)('aboriginally')('??');
console.log(pretty(with6Items));
const with7Items = insert(with6Items)('ab')('yup');
console.log(pretty(with7Items));
const with8Items = insert(with7Items)('')('hi!');
console.log(pretty(with8Items));
const with9Items = insert(with8Items)('fo')(42);
console.log(pretty(with9Items));
///////////////////
// Setup TRIE 2 ...
const bigTrie = module2Env(ModuleStd).name2dyn;
///////////////////
// Test...
// grow key (for auto-complete)
assert.equal(growPrefix(with6Items)("a" ), "b" );
assert.equal(growPrefix(with6Items)("ab" ), "" );
assert.equal(growPrefix(with6Items)("abb"), "a" );
assert.equal(growPrefix(with6Items)("f" ), "ood" );
assert.equal(growPrefix(with6Items)("abo"), "riginal");
// suggest (also for auto-complete)
assert.deepEqual(
suggest(with8Items)("a")(3),
[
[ 'ab', 'yup' ],
[ 'abba', 'dancing queen' ],
[ 'aboriginal', 'australia' ]
]);
assert.deepEqual(
suggest(with8Items)("a")(4),
[
[ 'ab', 'yup' ],
[ 'abba', 'dancing queen' ],
[ 'aboriginal', 'australia' ],
[ 'aboriginally', '??' ]
]);
assert.deepEqual(
suggest(with8Items)("a")(5),
[
[ 'ab', 'yup' ],
[ 'abba', 'dancing queen' ],
[ 'aboriginal', 'australia' ],
[ 'aboriginally', '??' ],
[ 'absent', 'not here' ]
]);
assert.deepEqual(
suggest(with8Items)("a")(15),
[
[ 'ab', 'yup' ],
[ 'abba', 'dancing queen' ],
[ 'aboriginal', 'australia' ],
[ 'aboriginally', '??' ],
[ 'absent', 'not here' ]
]);
assert.equal(
isProperlySorted(with9Items),
true,
"trie should always be properly sorted!"
);
assert.equal(
get(with9Items)(''),
"hi!"
)
assert.equal(
get(with9Items)('fo'),
42
)
assert.equal(
isProperlySorted(bigTrie),
true,
"trie should always be properly sorted!"
);
assert.equal(
growPrefix(bigTrie)("dict.le"),
"ngth"
);
assert.deepEqual(
suggest(bigTrie)("ooo")(2),
[]
);
assert.deepEqual(
suggest(bigTrie)("df")(2),
[]
);
assert.equal(
getInst(get(bigTrie)("list.push")),
push
);
assert.equal(
get(bigTrie)("ooo"),
undefined
);