2023-01-03 19:55:46 +00:00
|
|
|
// Copyright 2021 Signal Messenger, LLC
|
2021-12-06 23:06:13 +00:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2022-02-08 18:30:33 +00:00
|
|
|
import { every } from './iterables';
|
|
|
|
|
2021-12-06 23:06:13 +00:00
|
|
|
const add = <T>(set: Readonly<Set<T>>, item: T): Set<T> =>
|
|
|
|
new Set(set).add(item);
|
|
|
|
|
|
|
|
export const remove = <T>(
|
|
|
|
set: Readonly<Set<T>>,
|
|
|
|
...items: ReadonlyArray<T>
|
|
|
|
): Set<T> => {
|
|
|
|
const clone = new Set(set);
|
|
|
|
for (const item of items) {
|
|
|
|
clone.delete(item);
|
|
|
|
}
|
|
|
|
return clone;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const toggle = <T>(
|
|
|
|
set: Readonly<Set<T>>,
|
|
|
|
item: Readonly<T>,
|
|
|
|
shouldInclude: boolean
|
|
|
|
): Set<T> => (shouldInclude ? add : remove)(set, item);
|
2022-02-08 18:30:33 +00:00
|
|
|
|
|
|
|
export const isEqual = (
|
|
|
|
a: Readonly<Set<unknown>>,
|
|
|
|
b: Readonly<Set<unknown>>
|
|
|
|
): boolean => a === b || (a.size === b.size && every(a, item => b.has(item)));
|
2023-11-14 22:05:17 +00:00
|
|
|
|
|
|
|
export const difference = <T>(
|
|
|
|
a: Readonly<Set<T>>,
|
|
|
|
b: Readonly<Set<T>>
|
|
|
|
): Set<T> => {
|
|
|
|
const result = new Set([...a]);
|
|
|
|
for (const item of b) {
|
|
|
|
result.delete(item);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
};
|