From bce557cc2dc767628bed6aac87301a1be7c5431b Mon Sep 17 00:00:00 2001 From: rxliuli Date: Tue, 4 Nov 2025 05:03:50 +0800 Subject: init commit --- src/utils/array.ts | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/utils/array.ts (limited to 'src/utils/array.ts') 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( + input: Array, + predicate: (element: T) => boolean, +): [Array, Array] { + const left: Array = []; + const right: Array = []; + + 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(items: T[]): T[] { + const entries = items.map((item) => [item.id, item] as const); + const mapById = new Map(entries); + + return Array.from(mapById.values()); +} -- cgit v1.2.3