2020-08-04 22:57:37 +02:00
|
|
|
/*
|
2024-09-09 15:57:16 +02:00
|
|
|
Copyright 2024 New Vector Ltd.
|
2020-08-04 22:57:37 +02:00
|
|
|
Copyright 2020 The Matrix.org Foundation C.I.C.
|
|
|
|
|
2024-09-09 15:57:16 +02:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
|
|
|
|
Please see LICENSE files in the repository root for full details.
|
2020-08-04 22:57:37 +02:00
|
|
|
*/
|
|
|
|
|
2022-07-11 07:52:44 +02:00
|
|
|
import { arrayDiff, arrayIntersection } from "./arrays";
|
2020-08-04 22:57:37 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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.
|
2020-08-04 22:57:37 +02:00
|
|
|
*/
|
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[] } {
|
2020-08-04 22:57:37 +02:00
|
|
|
const aKeys = [...a.keys()];
|
|
|
|
const bKeys = [...b.keys()];
|
|
|
|
const keyDiff = arrayDiff(aKeys, bKeys);
|
2021-12-13 11:57:51 +01:00
|
|
|
const possibleChanges = arrayIntersection(aKeys, bKeys);
|
2022-12-12 12:24:14 +01:00
|
|
|
const changes = possibleChanges.filter((k) => a.get(k) !== b.get(k));
|
2020-08-04 22:57:37 +02:00
|
|
|
|
2021-06-29 14:11:58 +02:00
|
|
|
return { changed: changes, added: keyDiff.added, removed: keyDiff.removed };
|
2020-08-04 22:57:37 +02:00
|
|
|
}
|
|
|
|
|
2020-09-25 17:39:21 +02:00
|
|
|
/**
|
|
|
|
* 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)) {
|
2023-02-13 18:01:43 +01:00
|
|
|
return this.get(key)!;
|
2020-09-25 17:39:21 +02:00
|
|
|
}
|
|
|
|
this.set(key, def);
|
|
|
|
return def;
|
|
|
|
}
|
2020-09-27 02:40:26 +02:00
|
|
|
|
2023-02-13 18:01:43 +01: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;
|
|
|
|
}
|
2020-09-25 17:39:21 +02:00
|
|
|
}
|