diff --git a/collections/distinct.ts b/collections/distinct.ts index 5f117f204243..39d5b31f9df8 100644 --- a/collections/distinct.ts +++ b/collections/distinct.ts @@ -5,6 +5,8 @@ * Returns all distinct elements in the given array, preserving order by first * occurrence. * + * Uniqueness is determined by [same-value-zero](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality) equality. + * * @typeParam T The type of the elements in the input array. * * @param array The array to filter for distinct elements. diff --git a/collections/distinct_by.ts b/collections/distinct_by.ts index 7bc3972e0f0b..94482cc0e3ce 100644 --- a/collections/distinct_by.ts +++ b/collections/distinct_by.ts @@ -2,15 +2,17 @@ // This module is browser compatible. /** - * Returns all elements in the given array that produce a distinct value using - * the given selector, preserving order by first occurrence. + * Returns all elements in the given array that produce a unique value using + * the given discriminator, with the first matching occurrence retained. + * + * Uniqueness is determined by same-value-zero equality of the returned values. * * @typeParam T The type of the elements in the input array. - * @typeParam D The type of the values produced by the selector function. + * @typeParam D The type of the values produced by the discriminator function. * * @param array The array to filter for distinct elements. - * @param selector The function to extract the value to compare for - * distinctness. + * @param discriminator The function to extract the value to compare for + * uniqueness. * * @returns An array of distinct elements in the input array. * @@ -19,22 +21,22 @@ * import { distinctBy } from "@std/collections/distinct-by"; * import { assertEquals } from "@std/assert"; * - * const names = ["Anna", "Kim", "Arnold", "Kate"]; - * const exampleNamesByFirstLetter = distinctBy(names, (name) => name.charAt(0)); + * const users = [{ id: 1, name: "Anna" }, { id: 2, name: "Kim" }, { id: 1, name: "Anna again" }]; + * const uniqueUsers = distinctBy(users, (user) => user.id); * - * assertEquals(exampleNamesByFirstLetter, ["Anna", "Kim"]); + * assertEquals(uniqueUsers, [{ id: 1, name: "Anna" }, { id: 2, name: "Kim" }]); * ``` */ export function distinctBy( array: Iterable, - selector: (el: T) => D, + discriminator: (el: T) => D, ): T[] { - const selectedValues = new Set(); + const keys = new Set(); const result: T[] = []; for (const element of array) { - const selected = selector(element); - if (!selectedValues.has(selected)) { - selectedValues.add(selected); + const key = discriminator(element); + if (!keys.has(key)) { + keys.add(key); result.push(element); } }