riot-web/src/utils/maps.ts

50 lines
1.5 KiB
TypeScript
Raw Normal View History

/*
Copyright 2024 New Vector Ltd.
Copyright 2020 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
*/
2022-07-11 07:52:44 +02:00
import { arrayDiff, arrayIntersection } from "./arrays";
/**
* Determines the keys added, changed, and removed between two Maps.
2020-08-04 23:03:30 +02:00
* For changes, simple triple equal comparisons are done, not in-depth tree checking.
* @param a The first Map. Must be defined.
* @param b The second Map. Must be defined.
* @returns The difference between the keys of each Map.
*/
2022-12-12 12:24:14 +01:00
export function mapDiff<K, V>(a: Map<K, V>, b: Map<K, V>): { changed: K[]; added: K[]; removed: K[] } {
const aKeys = [...a.keys()];
const bKeys = [...b.keys()];
const keyDiff = arrayDiff(aKeys, bKeys);
const possibleChanges = arrayIntersection(aKeys, bKeys);
2022-12-12 12:24:14 +01:00
const changes = possibleChanges.filter((k) => a.get(k) !== b.get(k));
2021-06-29 14:11:58 +02:00
return { changed: changes, added: keyDiff.added, removed: keyDiff.removed };
}
/**
* A Map<K, V> with added utility.
*/
export class EnhancedMap<K, V> extends Map<K, V> {
public constructor(entries?: Iterable<[K, V]>) {
super(entries);
}
public getOrCreate(key: K, def: V): V {
if (this.has(key)) {
return this.get(key)!;
}
this.set(key, def);
return def;
}
2020-09-27 02:40:26 +02:00
public remove(key: K): V | undefined {
2020-09-27 02:40:26 +02:00
const v = this.get(key);
this.delete(key);
return v;
}
}