Repository navigation
Expand file tree
/
Copy pathlist.js
More file actions
81 lines (69 loc) · 1.95 KB
/
Copy pathlist.js
File metadata and controls
81 lines (69 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// list.js — Keyed list helper for feeds. Keyed append/update/remove/clear.
// No virtual DOM. Zero dependencies.
//
// const list = new KeyedList(ul, (msg) => msg.id, (msg) => {
// const li = document.createElement('li');
// li.textContent = msg.text;
// return li;
// });
// list.upsert({ id: 1, text: 'hello' });
const defaultRender = (item) => {
const el = document.createElement('div');
el.textContent = String(item);
return el;
};
export class KeyedList {
#parent;
#keyFn;
#render;
#map = new Map(); // key -> element
/**
* @param parent element the items are rendered into
* @param keyFn item -> unique key
* @param render item -> Element (default: a <div> with String(item) as text).
* Items that already are Elements are inserted as they are.
*/
constructor(parent, keyFn, render = defaultRender) {
this.#parent = parent;
this.#keyFn = keyFn;
this.#render = render;
}
#element(item) {
return item instanceof Element ? item : this.#render(item);
}
/** Add an item at the end; an item whose key exists is replaced in place. */
append(item) {
return this.upsert(item);
}
/** Replace the item with the same key in place (appends if missing). */
update(item) {
return this.upsert(item);
}
upsert(item) {
const key = this.#keyFn(item);
const existing = this.#map.get(key);
const el = this.#element(item);
if (existing?.parentNode === this.#parent) existing.replaceWith(el);
else this.#parent.append(el);
this.#map.set(key, el);
return el;
}
remove(key) {
this.#map.get(key)?.remove();
this.#map.delete(key);
}
/** Remove every item this list added; other children of parent stay. */
clear() {
for (const el of this.#map.values()) el.remove();
this.#map.clear();
}
has(key) {
return this.#map.has(key);
}
get(key) {
return this.#map.get(key);
}
get size() {
return this.#map.size;
}
}