summaryrefslogtreecommitdiff
path: root/src/utils/array.ts
diff options
context:
space:
mode:
authorrxliuli <rxliuli@gmail.com>2025-11-04 05:03:50 +0800
committerrxliuli <rxliuli@gmail.com>2025-11-04 05:03:50 +0800
commitbce557cc2dc767628bed6aac87301a1be7c5431b (patch)
treeb51a051228d01fe3306cd7626d4a96768aadb944 /src/utils/array.ts
init commit
Diffstat (limited to 'src/utils/array.ts')
-rw-r--r--src/utils/array.ts33
1 files changed, 33 insertions, 0 deletions
diff --git a/src/utils/array.ts b/src/utils/array.ts
new file mode 100644
index 0000000..de9ef96
--- /dev/null
+++ b/src/utils/array.ts
@@ -0,0 +1,33 @@
+/**
+ * Split an array into two groups based on the result {@linkcode predicate}
+ *
+ * Items for which {@linkcode predicate} returns `true` will be in the "left"
+ * result, and the others in the "right" one
+ */
+export function partition<T>(
+ input: Array<T>,
+ predicate: (element: T) => boolean,
+): [Array<T>, Array<T>] {
+ const left: Array<T> = [];
+ const right: Array<T> = [];
+
+ for (const element of input) {
+ if (predicate(element)) {
+ left.push(element);
+ } else {
+ right.push(element);
+ }
+ }
+
+ return [left, right];
+}
+
+/**
+ * Deduplicate the elements of {@linkcode items} by their `id` property
+ */
+export function uniqueById<T extends { id: string }>(items: T[]): T[] {
+ const entries = items.map((item) => [item.id, item] as const);
+ const mapById = new Map<string, T>(entries);
+
+ return Array.from(mapById.values());
+}