From 735b2b431f6bcea281ae248686aee0f6279b797e Mon Sep 17 00:00:00 2001 From: Maciej Hirsz <1096222+maciejhirsz@users.noreply.github.com> Date: Sat, 9 Nov 2019 15:19:16 +0100 Subject: [PATCH] feat: Use array for node map (#197) * feat: Use array for node map * fix: Map growing --- packages/common/src/SortedCollection.ts | 32 +++++++++++++++---------- packages/frontend/src/state.ts | 2 +- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/packages/common/src/SortedCollection.ts b/packages/common/src/SortedCollection.ts index b62a2a3..a5e9680 100644 --- a/packages/common/src/SortedCollection.ts +++ b/packages/common/src/SortedCollection.ts @@ -89,10 +89,10 @@ export namespace SortedCollection { export type StateRef = Opaque; } -export class SortedCollection { - private readonly map = new Map(); +export class SortedCollection { private readonly compare: Compare; + private map = Array>(); private list = Array(); private changeRef = 0; @@ -105,14 +105,20 @@ export class SortedCollection { } public add(item: Item) { - this.map.set(item.id, item); + if (this.map.length <= item.id) { + // Grow map if item.id would be out of scope + this.map = this.map.concat(Array>(Math.max(10, 1 + item.id - this.map.length))); + } + + this.map[item.id] = item; + sortedInsert(item, this.list, this.compare); this.changeRef += 1; } - public remove(id: Id) { - const item = this.map.get(id); + public remove(id: number) { + const item = this.map[id]; if (!item) { return; @@ -120,21 +126,21 @@ export class SortedCollection { const index = sortedIndexOf(item, this.list, this.compare); this.list.splice(index, 1); - this.map.delete(id); + this.map[id] = null; this.changeRef += 1; } - public get(id: Id): Maybe { - return this.map.get(id); + public get(id: number): Maybe { + return this.map[id]; } public sorted(): Array { return this.list; } - public mut(id: Id, mutator: (item: Item) => void) { - const item = this.map.get(id); + public mut(id: number, mutator: (item: Item) => void) { + const item = this.map[id]; if (!item) { return; @@ -143,8 +149,8 @@ export class SortedCollection { mutator(item); } - public mutAndSort(id: Id, mutator: (item: Item) => void) { - const item = this.map.get(id); + public mutAndSort(id: number, mutator: (item: Item) => void) { + const item = this.map[id]; if (!item) { return; @@ -173,7 +179,7 @@ export class SortedCollection { } public clear() { - this.map.clear(); + this.map = []; this.list = []; this.changeRef += 1; diff --git a/packages/frontend/src/state.ts b/packages/frontend/src/state.ts index ebfe95d..4562a3f 100644 --- a/packages/frontend/src/state.ts +++ b/packages/frontend/src/state.ts @@ -220,7 +220,7 @@ export interface State { timeDiff: Types.Milliseconds; subscribed: Maybe; chains: Map; - nodes: SortedCollection; + nodes: SortedCollection; settings: Readonly; pins: Readonly>; }