fix dict
This commit is contained in:
@@ -0,0 +1,33 @@
|
|||||||
|
import { expect, test } from "vitest";
|
||||||
|
import {
|
||||||
|
createDictionary,
|
||||||
|
type Dictionary,
|
||||||
|
deleteEntrySave,
|
||||||
|
forEntry,
|
||||||
|
getEntry,
|
||||||
|
setEntrySave,
|
||||||
|
} from "./Dictionary.ts";
|
||||||
|
|
||||||
|
test("Dictionary", () => {
|
||||||
|
const dict: Dictionary<string, number> = createDictionary([
|
||||||
|
["a", 1],
|
||||||
|
["b", 2],
|
||||||
|
["c", 3],
|
||||||
|
]);
|
||||||
|
setEntrySave(dict, "foo", 42);
|
||||||
|
setEntrySave(dict, "bar", 0);
|
||||||
|
deleteEntrySave(dict, "bar");
|
||||||
|
|
||||||
|
console.table(dict.entries);
|
||||||
|
console.table(dict.indices);
|
||||||
|
|
||||||
|
expect(getEntry(dict, "foo")).toBe(42);
|
||||||
|
expect(getEntry(dict, "bar")).toBe(undefined);
|
||||||
|
expect(dict.indices.size).toBe(dict.entries.length);
|
||||||
|
|
||||||
|
let sum = 0;
|
||||||
|
forEntry(dict, (value) => {
|
||||||
|
sum += value;
|
||||||
|
});
|
||||||
|
expect(sum).toBe(48);
|
||||||
|
});
|
||||||
@@ -6,10 +6,15 @@ export type Dictionary<K, V> = {
|
|||||||
setQueue: Array<[K, V]>;
|
setQueue: Array<[K, V]>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createDictionary<K, V>(): Dictionary<K, V> {
|
export function createDictionary<K, V>(
|
||||||
|
iterable?: Iterable<[K, V]>,
|
||||||
|
): Dictionary<K, V> {
|
||||||
|
const entries = iterable ? [...iterable] : [];
|
||||||
|
const indices = new Map(entries.map(([k], i) => [k, i]));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
entries: [],
|
entries,
|
||||||
indices: new Map(),
|
indices,
|
||||||
isIterating: false,
|
isIterating: false,
|
||||||
deleteQueue: [],
|
deleteQueue: [],
|
||||||
setQueue: [],
|
setQueue: [],
|
||||||
@@ -46,8 +51,8 @@ export function setEntry<K, V>(
|
|||||||
): void {
|
): void {
|
||||||
const index = dict.indices.get(key);
|
const index = dict.indices.get(key);
|
||||||
if (index === undefined) {
|
if (index === undefined) {
|
||||||
dict.entries.push([key, value]);
|
|
||||||
dict.indices.set(key, dict.entries.length);
|
dict.indices.set(key, dict.entries.length);
|
||||||
|
dict.entries.push([key, value]);
|
||||||
} else {
|
} else {
|
||||||
dict.entries[index][1] = value;
|
dict.entries[index][1] = value;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user