diff --git a/_tools/check_docs.ts b/_tools/check_docs.ts index c81fed2445ca..dfa3f07e41f9 100644 --- a/_tools/check_docs.ts +++ b/_tools/check_docs.ts @@ -20,6 +20,7 @@ import type { const ENTRY_POINTS = [ "../bytes/mod.ts", "../datetime/mod.ts", + "../collections/mod.ts", ] as const; const MD_SNIPPET = /(?<=```ts\n)(\n|.)*(?=\n```)/g; @@ -44,7 +45,9 @@ function assert( } function isFunctionDoc(document: DocNodeBase): document is DocNodeFunction { - return document.kind === "function"; + return document.kind === "function" && + // Ignores implementation signatures when overload signatures exist + (document as DocNodeFunction).functionDef.hasBody !== true; } function isExported(document: DocNodeBase) { diff --git a/collections/aggregate_groups.ts b/collections/aggregate_groups.ts index 5b246b0c0400..e5b76550d573 100644 --- a/collections/aggregate_groups.ts +++ b/collections/aggregate_groups.ts @@ -7,31 +7,38 @@ import { mapEntries } from "./map_entries.ts"; * Applies the given aggregator to each group in the given grouping, returning the * results together with the respective group keys * - * @template T input type of an item in a group in the given grouping. - * @template A type of the accumulator value, which will match the returned record's values. - * @example + * @template T Type of the values in the input record. + * @template A Type of the accumulator value, which will match the returned + * record's values. + * + * @param record The grouping to aggregate. + * @param aggregator The function to apply to each group. + * + * @returns A record with the same keys as the input record, but with the values + * being the result of applying the aggregator to each group. + * + * @example Basic usage * ```ts * import { aggregateGroups } from "@std/collections/aggregate-groups"; * import { assertEquals } from "@std/assert/assert-equals"; * * const foodProperties = { - * "Curry": ["spicy", "vegan"], - * "Omelette": ["creamy", "vegetarian"], + * Curry: ["spicy", "vegan"], + * Omelette: ["creamy", "vegetarian"], * }; + * * const descriptions = aggregateGroups( * foodProperties, * (current, key, first, acc) => { - * if (first) { - * return `${key} is ${current}`; - * } - * - * return `${acc} and ${current}`; + * return first + * ? `${key} is ${current}` + * : `${acc} and ${current}`; * }, * ); * * assertEquals(descriptions, { - * "Curry": "Curry is spicy and vegan", - * "Omelette": "Omelette is creamy and vegetarian", + * Curry: "Curry is spicy and vegan", + * Omelette: "Omelette is creamy and vegetarian", * }); * ``` */ @@ -43,7 +50,8 @@ export function aggregateGroups( record, ([key, values]) => [ key, - // Need the type assertions here because the reduce type does not support the type transition we need + // Need the type assertions here because the reduce type does not support + // the type transition we need values.reduce( (accumulator, current, currentIndex) => aggregator(current, key, currentIndex === 0, accumulator), diff --git a/collections/associate_by.ts b/collections/associate_by.ts index 5d0b64c1116d..fff3c9701152 100644 --- a/collections/associate_by.ts +++ b/collections/associate_by.ts @@ -2,11 +2,21 @@ // This module is browser compatible. /** - * Transforms the given array into a Record, extracting the key of each element - * using the given selector. If the selector produces the same key for multiple - * elements, the latest one will be used (overriding the ones before it). + * Creates a record by associating each element of the input array with a key + * generated by the selector function. * - * @example + * If the selector produces the same key for multiple elements, the latest one + * will be used (overriding the ones before it). + * + * @template T Type of the elements in the input array. + * + * @param array The array to transform. + * @param selector The function to extract the key from each element. + * + * @returns A record with the keys produced by the selector and the elements as + * values. + * + * @example Basic usage * ```ts * import { associateBy } from "@std/collections/associate-by"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -16,7 +26,8 @@ * { id: "5f8", userName: "Arnold" }, * { id: "d2c", userName: "Kim" }, * ]; - * const usersById = associateBy(users, (it) => it.id); + * + * const usersById = associateBy(users, (user) => user.id); * * assertEquals(usersById, { * "a2e": { id: "a2e", userName: "Anna" }, diff --git a/collections/associate_with.ts b/collections/associate_with.ts index a31746dc5e32..d495e8f9fec1 100644 --- a/collections/associate_with.ts +++ b/collections/associate_with.ts @@ -2,17 +2,28 @@ // This module is browser compatible. /** - * Builds a new Record using the given array as keys and choosing a value for - * each key using the given selector. If any of two pairs would have the same - * value the latest on will be used (overriding the ones before it). + * Associates each element of an array with a value returned by a selector + * function. * - * @example + * If any of two pairs would have the same value the latest on will be used + * (overriding the ones before it). + * + * @template T The type of the values returned by the selector function. + * + * @param array The array of elements to associate with values. + * @param selector The selector function that returns a value for each element. + * + * @returns An object where each element of the array is associated with a value + * returned by the selector function. + * + * @example Basic usage * ```ts * import { associateWith } from "@std/collections/associate-with"; * import { assertEquals } from "@std/assert/assert-equals"; * * const names = ["Kim", "Lara", "Jonathan"]; - * const namesToLength = associateWith(names, (it) => it.length); + * + * const namesToLength = associateWith(names, (person) => person.length); * * assertEquals(namesToLength, { * "Kim": 3, diff --git a/collections/chunk.ts b/collections/chunk.ts index ac584abb1000..95a075a1efdb 100644 --- a/collections/chunk.ts +++ b/collections/chunk.ts @@ -4,7 +4,14 @@ /** * Splits the given array into chunks of the given size and returns them. * - * @example + * @template T Type of the elements in the input array. + * + * @param array The array to split into chunks. + * @param size The size of the chunks. This my be a positive integer. + * + * @returns An array of chunks of the given size. + * + * @example Basic usage * ```ts * import { chunk } from "@std/collections/chunk"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/deep_merge.ts b/collections/deep_merge.ts index 0d6cf54c8257..a1535444914c 100644 --- a/collections/deep_merge.ts +++ b/collections/deep_merge.ts @@ -6,14 +6,21 @@ import { filterInPlace } from "./_utils.ts"; const { hasOwn } = Object; /** - * Merges the two given Records, recursively merging any nested Records with the - * second collection overriding the first in case of conflict + * Merges the two given records, recursively merging any nested records with the + * second collection overriding the first in case of conflict. * * For arrays, maps and sets, a merging strategy can be specified to either - * `replace` values, or `merge` them instead. Use `includeNonEnumerable` option - * to include non-enumerable properties too. + * `replace` values, or `merge` them instead. * - * @example + * @template T Type of the first record + * + * @param record First record to merge. + * @param other Second record to merge. + * @param options Merging options. + * + * @returns A new record with the merged values. + * + * @example Merge objects * ```ts * import { deepMerge } from "@std/collections/deep-merge"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -21,7 +28,71 @@ const { hasOwn } = Object; * const a = { foo: true }; * const b = { foo: { bar: true } }; * - * assertEquals(deepMerge(a, b), { foo: { bar: true } }); + * const result = deepMerge(a, b); + * + * const expected = { foo: { bar: true } }; + * + * assertEquals(result, expected); + * ``` + * + * @example Merge arrays + * ```ts + * import { deepMerge } from "@std/collections/deep-merge"; + * import { assertEquals } from "@std/assert/assert-equals"; + * + * const a = { foo: [1, 2] }; + * const b = { foo: [3, 4] }; + * + * const result = deepMerge(a, b); + * + * const expected = { foo: [1, 2, 3, 4] }; + * + * assertEquals(result, expected); + * ``` + * + * @example Merge maps + * ```ts + * import { deepMerge } from "@std/collections/deep-merge"; + * import { assertEquals } from "@std/assert/assert-equals"; + * + * const a = { foo: new Map([["a", 1]]) }; + * const b = { foo: new Map([["b", 2]]) }; + * + * const result = deepMerge(a, b); + * + * const expected = { foo: new Map([["a", 1], ["b", 2]]) }; + * + * assertEquals(result, expected); + * ``` + * + * @example Merge sets + * ```ts + * import { deepMerge } from "@std/collections/deep-merge"; + * import { assertEquals } from "@std/assert/assert-equals"; + * + * const a = { foo: new Set([1]) }; + * const b = { foo: new Set([2]) }; + * + * const result = deepMerge(a, b); + * + * const expected = { foo: new Set([1, 2]) }; + * + * assertEquals(result, expected); + * ``` + * + * @example Merge with custom options + * ```ts + * import { deepMerge } from "@std/collections/deep-merge"; + * import { assertEquals } from "@std/assert/assert-equals"; + * + * const a = { foo: [1, 2] }; + * const b = { foo: [3, 4] }; + * + * const result = deepMerge(a, b, { arrays: "replace" }); + * + * const expected = { foo: [3, 4] }; + * + * assertEquals(result, expected); * ``` */ export function deepMerge< @@ -32,14 +103,23 @@ export function deepMerge< options?: Readonly, ): T; /** - * Merges the two given Records, recursively merging any nested Records with the - * second collection overriding the first in case of conflict + * Merges the two given records, recursively merging any nested records with the + * second collection overriding the first in case of conflict. * * For arrays, maps and sets, a merging strategy can be specified to either - * `replace` values, or `merge` them instead. Use `includeNonEnumerable` option - * to include non-enumerable properties too. + * `replace` values, or `merge` them instead. + * + * @template T Type of the first record + * @template U Type of the second record + * @template Options Merging options * - * @example + * @param record First record to merge. + * @param other Second record to merge. + * @param options Merging options. + * + * @returns A new record with the merged values. + * + * @example Merge objects * ```ts * import { deepMerge } from "@std/collections/deep-merge"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -47,7 +127,71 @@ export function deepMerge< * const a = { foo: true }; * const b = { foo: { bar: true } }; * - * assertEquals(deepMerge(a, b), { foo: { bar: true } }); + * const result = deepMerge(a, b); + * + * const expected = { foo: { bar: true } }; + * + * assertEquals(result, expected); + * ``` + * + * @example Merge arrays + * ```ts + * import { deepMerge } from "@std/collections/deep-merge"; + * import { assertEquals } from "@std/assert/assert-equals"; + * + * const a = { foo: [1, 2] }; + * const b = { foo: [3, 4] }; + * + * const result = deepMerge(a, b); + * + * const expected = { foo: [1, 2, 3, 4] }; + * + * assertEquals(result, expected); + * ``` + * + * @example Merge maps + * ```ts + * import { deepMerge } from "@std/collections/deep-merge"; + * import { assertEquals } from "@std/assert/assert-equals"; + * + * const a = { foo: new Map([["a", 1]]) }; + * const b = { foo: new Map([["b", 2]]) }; + * + * const result = deepMerge(a, b); + * + * const expected = { foo: new Map([["a", 1], ["b", 2]]) }; + * + * assertEquals(result, expected); + * ``` + * + * @example Merge sets + * ```ts + * import { deepMerge } from "@std/collections/deep-merge"; + * import { assertEquals } from "@std/assert/assert-equals"; + * + * const a = { foo: new Set([1]) }; + * const b = { foo: new Set([2]) }; + * + * const result = deepMerge(a, b); + * + * const expected = { foo: new Set([1, 2]) }; + * + * assertEquals(result, expected); + * ``` + * + * @example Merge with custom options + * ```ts + * import { deepMerge } from "@std/collections/deep-merge"; + * import { assertEquals } from "@std/assert/assert-equals"; + * + * const a = { foo: [1, 2] }; + * const b = { foo: [3, 4] }; + * + * const result = deepMerge(a, b, { arrays: "replace" }); + * + * const expected = { foo: [3, 4] }; + * + * assertEquals(result, expected); * ``` */ export function deepMerge< @@ -59,7 +203,6 @@ export function deepMerge< other: Readonly, options?: Readonly, ): DeepMerge; - export function deepMerge< T extends Record, U extends Record, @@ -226,13 +369,25 @@ function getKeys>(record: T): Array { /** Merging strategy */ export type MergingStrategy = "replace" | "merge"; -/** Deep merge options */ +/** Options for {@linkcode deepMerge}. */ export type DeepMergeOptions = { - /** Merging strategy for arrays */ + /** + * Merging strategy for arrays + * + * @default {"merge"} + */ arrays?: MergingStrategy; - /** Merging strategy for Maps */ + /** + * Merging strategy for maps. + * + * @default {"merge"} + */ maps?: MergingStrategy; - /** Merging strategy for Sets */ + /** + * Merging strategy for sets. + * + * @default {"merge"} + */ sets?: MergingStrategy; }; diff --git a/collections/distinct.ts b/collections/distinct.ts index b264438a7869..8c57b52cb2da 100644 --- a/collections/distinct.ts +++ b/collections/distinct.ts @@ -5,7 +5,13 @@ * Returns all distinct elements in the given array, preserving order by first * occurrence. * - * @example + * @template T The type of the elements in the input array. + * + * @param array The array to filter for distinct elements. + * + * @returns An array of distinct elements in the input array. + * + * @example Basic usage * ```ts * import { distinct } from "@std/collections/distinct"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/distinct_by.ts b/collections/distinct_by.ts index 876546dab711..4029713e34a8 100644 --- a/collections/distinct_by.ts +++ b/collections/distinct_by.ts @@ -5,13 +5,22 @@ * Returns all elements in the given array that produce a distinct value using * the given selector, preserving order by first occurrence. * - * @example + * @template T The type of the elements in the input array. + * @template D The type of the values produced by the selector function. + * + * @param array The array to filter for distinct elements. + * @param selector The function to extract the value to compare for + * distinctness. + * + * @returns An array of distinct elements in the input array. + * + * @example Basic usage * ```ts * import { distinctBy } from "@std/collections/distinct-by"; * import { assertEquals } from "@std/assert/assert-equals"; * * const names = ["Anna", "Kim", "Arnold", "Kate"]; - * const exampleNamesByFirstLetter = distinctBy(names, (it) => it.charAt(0)); + * const exampleNamesByFirstLetter = distinctBy(names, (name) => name.charAt(0)); * * assertEquals(exampleNamesByFirstLetter, ["Anna", "Kim"]); * ``` diff --git a/collections/drop_last_while.ts b/collections/drop_last_while.ts index 14814c67caa8..ea5f2063e9fb 100644 --- a/collections/drop_last_while.ts +++ b/collections/drop_last_while.ts @@ -5,19 +5,24 @@ * Returns a new array that drops all elements in the given collection until the * last element that does not match the given predicate. * - * @example + * @template T The type of the elements in the input array. + * + * @param array The array to drop elements from. + * @param predicate The function to test each element for a condition. + * + * @returns A new array that drops all elements until the last element that does + * not match the given predicate. + * + * @example Basic usage * ```ts * import { dropLastWhile } from "@std/collections/drop-last-while"; * import { assertEquals } from "@std/assert/assert-equals"; * * const numbers = [22, 30, 44]; * - * const notFortyFour = dropLastWhile(numbers, (i) => i !== 44); + * const notFortyFour = dropLastWhile(numbers, (number) => number !== 44); * - * assertEquals( - * notFortyFour, - * [22, 30], - * ); + * assertEquals(notFortyFour, [22, 30]); * ``` */ export function dropLastWhile( diff --git a/collections/drop_while.ts b/collections/drop_while.ts index 508f474fac2b..4a4655ff2cb8 100644 --- a/collections/drop_while.ts +++ b/collections/drop_while.ts @@ -5,13 +5,21 @@ * Returns a new array that drops all elements in the given collection until the * first element that does not match the given predicate. * - * @example + * @template T The type of the elements in the input array. + * + * @param array The array to drop elements from. + * @param predicate The function to test each element for a condition. + * + * @returns A new array that drops all elements until the first element that + * does not match the given predicate. + * + * @example Basic usage * ```ts * import { dropWhile } from "@std/collections/drop-while"; * import { assertEquals } from "@std/assert/assert-equals"; * * const numbers = [3, 2, 5, 2, 5]; - * const dropWhileNumbers = dropWhile(numbers, (i) => i !== 2); + * const dropWhileNumbers = dropWhile(numbers, (number) => number !== 2); * * assertEquals(dropWhileNumbers, [2, 5, 2, 5]); * ``` diff --git a/collections/filter_entries.ts b/collections/filter_entries.ts index 08cb8243ba8f..acf7b80c49c1 100644 --- a/collections/filter_entries.ts +++ b/collections/filter_entries.ts @@ -5,27 +5,30 @@ * Returns a new record with all entries of the given record except the ones * that do not match the given predicate. * - * @example + * @template T The type of the values in the input record. + * + * @param record The record to filter entries from. + * @param predicate The function to test each entry for a condition. + * + * @returns A new record with all entries that match the given predicate. + * + * @example Basic usage * ```ts * import { filterEntries } from "@std/collections/filter-entries"; * import { assertEquals } from "@std/assert/assert-equals"; * * const menu = { - * "Salad": 11, - * "Soup": 8, - * "Pasta": 13, - * } as const; + * Salad: 11, + * Soup: 8, + * Pasta: 13, + * }; + * * const myOptions = filterEntries( * menu, * ([item, price]) => item !== "Pasta" && price < 10, * ); * - * assertEquals( - * myOptions, - * { - * "Soup": 8, - * }, - * ); + * assertEquals(myOptions, { Soup: 8 }); * ``` */ export function filterEntries( diff --git a/collections/filter_keys.ts b/collections/filter_keys.ts index 3dc62ea3e2a0..fb915ea78f81 100644 --- a/collections/filter_keys.ts +++ b/collections/filter_keys.ts @@ -5,23 +5,32 @@ * Returns a new record with all entries of the given record except the ones that * have a key that does not match the given predicate. * - * @example + * @template T The type of the values in the input record. + * + * @param record The record to filter keys from. + * @param predicate The function to test each key for a condition. + * + * @returns A new record with all entries that have a key that matches the given + * predicate. + * + * @example Basic usage * ```ts * import { filterKeys } from "@std/collections/filter-keys"; * import { assertEquals } from "@std/assert/assert-equals"; * * const menu = { - * "Salad": 11, - * "Soup": 8, - * "Pasta": 13, + * Salad: 11, + * Soup: 8, + * Pasta: 13, * }; - * const menuWithoutSalad = filterKeys(menu, (it) => it !== "Salad"); + * + * const menuWithoutSalad = filterKeys(menu, (item) => item !== "Salad"); * * assertEquals( * menuWithoutSalad, * { - * "Soup": 8, - * "Pasta": 13, + * Soup: 8, + * Pasta: 13, * }, * ); * ``` diff --git a/collections/filter_values.ts b/collections/filter_values.ts index 8eecd2f88754..94f721fac59e 100644 --- a/collections/filter_values.ts +++ b/collections/filter_values.ts @@ -5,23 +5,31 @@ * Returns a new record with all entries of the given record except the ones * that have a value that does not match the given predicate. * - * @example + * @template T The type of the values in the input record. + * + * @param record The record to filter values from. + * @param predicate The function to test each value for a condition. + * + * @returns A new record with all entries that have a value that matches the + * given predicate. + * + * @example Basic usage * ```ts * import { filterValues } from "@std/collections/filter-values"; * import { assertEquals } from "@std/assert/assert-equals"; * * const people = { - * "Arnold": 37, - * "Sarah": 7, - * "Kim": 23, + * Arnold: 37, + * Sarah: 7, + * Kim: 23, * }; - * const adults = filterValues(people, (it) => it >= 18); + * const adults = filterValues(people, (person) => person >= 18); * * assertEquals( * adults, * { - * "Arnold": 37, - * "Kim": 23, + * Arnold: 37, + * Kim: 23, * }, * ); * ``` diff --git a/collections/find_single.ts b/collections/find_single.ts index f06cfca303e3..4eb589b9bf7d 100644 --- a/collections/find_single.ts +++ b/collections/find_single.ts @@ -5,7 +5,15 @@ * Returns an element if and only if that element is the only one matching the * given condition. Returns `undefined` otherwise. * - * @example + * @template T The type of the elements in the input array. + * + * @param array The array to find a single element in. + * @param predicate The function to test each element for a condition. + * + * @returns The single element that matches the given condition or `undefined` + * if there are zero or more than one matching elements. + * + * @example Basic usage * ```ts * import { findSingle } from "@std/collections/find-single"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -15,11 +23,11 @@ * { month: "March", active: false }, * { month: "June", active: true }, * ]; - * const activeBooking = findSingle(bookings, (it) => it.active); - * const inactiveBooking = findSingle(bookings, (it) => !it.active); + * const activeBooking = findSingle(bookings, (booking) => booking.active); + * const inactiveBooking = findSingle(bookings, (booking) => !booking.active); * * assertEquals(activeBooking, { month: "June", active: true }); - * assertEquals(inactiveBooking, undefined); // there are two applicable items + * assertEquals(inactiveBooking, undefined); // There are two applicable items * ``` */ export function findSingle( diff --git a/collections/first_not_nullish_of.ts b/collections/first_not_nullish_of.ts index 95e9a5fa9869..04ef0c5108c7 100644 --- a/collections/first_not_nullish_of.ts +++ b/collections/first_not_nullish_of.ts @@ -6,7 +6,16 @@ * produced that is neither `null` nor `undefined` and returns that value. * Returns `undefined` if no such value is produced. * - * @example + * @template T The type of the elements in the input array. + * @template O The type of the value produced by the selector function. + * + * @param array The array to select a value from. + * @param selector The function to extract a value from an element. + * + * @returns The first non-`null` and non-`undefined` value produced by the + * selector function, or `undefined` if no such value is produced. + * + * @example Basic usage * ```ts * import { firstNotNullishOf } from "@std/collections/first-not-nullish-of"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -16,6 +25,7 @@ * { number: 12, order: "Soup" }, * { number: 13, order: "Salad" }, * ]; + * * const nextOrder = firstNotNullishOf(tables, (it) => it.order); * * assertEquals(nextOrder, "Soup"); diff --git a/collections/includes_value.ts b/collections/includes_value.ts index 8773dd4b940f..a78cca5aaeec 100644 --- a/collections/includes_value.ts +++ b/collections/includes_value.ts @@ -2,11 +2,20 @@ // This module is browser compatible. /** - * If the given value is part of the given object it returns true, otherwise it - * returns false. Doesn't work with non-primitive values: includesValue({x: {}}, - * {}) returns false. + * Returns true if the given value is part of the given object, otherwise it + * returns false. * - * @example + * Note: this doesn't work with non-primitive values. For example, + * `includesValue({x: {}}, {})` returns false. + * + * @template T The type of the values in the input record. + * + * @param record The record to check for the given value. + * @param value The value to check for in the record. + * + * @returns `true` if the value is part of the record, otherwise `false`. + * + * @example Basic usage * ```ts * import { includesValue } from "@std/collections/includes-value"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/intersect.ts b/collections/intersect.ts index ec4557c7a589..71e7ebfbf73c 100644 --- a/collections/intersect.ts +++ b/collections/intersect.ts @@ -7,7 +7,14 @@ import { filterInPlace } from "./_utils.ts"; * Returns all distinct elements that appear at least once in each of the given * arrays. * - * @example + * @template T The type of the elements in the input arrays. + * + * @param arrays The arrays to intersect. + * + * @returns An array of distinct elements that appear at least once in each of + * the given arrays. + * + * @example Basic usage * ```ts * import { intersect } from "@std/collections/intersect"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/join_to_string.ts b/collections/join_to_string.ts index f5f868839d96..e1fe4425c510 100644 --- a/collections/join_to_string.ts +++ b/collections/join_to_string.ts @@ -3,10 +3,36 @@ /** Options for {@linkcode joinToString}. */ export type JoinToStringOptions = { + /** + * The string to use as a separator between the elements. + * + * @default {","} + */ separator?: string; + /** + * The string to use as a prefix for the resulting string. + * + * @default {""} + */ prefix?: string; + /** + * The string to use as a suffix for the resulting string. + * + * @default {""} + */ suffix?: string; + /** + * The maximum number of elements to append. If the value is negative, all + * elements will be appended, which is the default. + * + * @default {-1} + */ limit?: number; + /** + * The string to use as a placeholder for the truncated elements. + * + * @default {"..."} + */ truncated?: string; }; @@ -14,11 +40,20 @@ export type JoinToStringOptions = { * Transforms the elements in the given array to strings using the given * selector. Joins the produced strings into one using the given `separator` * and applying the given `prefix` and `suffix` to the whole string afterwards. + * * If the array could be huge, you can specify a non-negative value of `limit`, * in which case only the first `limit` elements will be appended, followed by - * the `truncated` string. Returns the resulting string. + * the `truncated` string. + * + * @template T The type of the elements in the input array. + * + * @param array The array to join elements from. + * @param selector The function to transform elements to strings. + * @param options The options to configure the joining. + * + * @returns The resulting string. * - * @example + * @example Usage with options * ```ts * import { joinToString } from "@std/collections/join-to-string"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -43,14 +78,16 @@ export type JoinToStringOptions = { export function joinToString( array: Iterable, selector: (el: T) => string, - { + options: Readonly = {}, +): string { + const { separator = ",", prefix = "", suffix = "", limit = -1, truncated = "...", - }: Readonly = {}, -): string { + } = options; + let result = ""; let index = -1; diff --git a/collections/map_entries.ts b/collections/map_entries.ts index 3d5874b33cd2..34025d5b70a1 100644 --- a/collections/map_entries.ts +++ b/collections/map_entries.ts @@ -5,7 +5,15 @@ * Applies the given transformer to all entries in the given record and returns * a new record containing the results. * - * @example + * @template T The type of the values in the input record. + * @template O The type of the values in the output record. + * + * @param record The record to map entries from. + * @param transformer The function to transform each entry. + * + * @returns A new record with all entries transformed by the given transformer. + * + * @example Basic usage * ```ts * import { mapEntries } from "@std/collections/map-entries"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -14,15 +22,16 @@ * "a2e": { name: "Kim", age: 22 }, * "dfe": { name: "Anna", age: 31 }, * "34b": { name: "Tim", age: 58 }, - * } as const; + * }; + * * const agesByNames = mapEntries(usersById, ([id, { name, age }]) => [name, age]); * * assertEquals( * agesByNames, * { - * "Kim": 22, - * "Anna": 31, - * "Tim": 58, + * Kim: 22, + * Anna: 31, + * Tim: 58, * }, * ); * ``` diff --git a/collections/map_keys.ts b/collections/map_keys.ts index 14b73c68ed36..8365c025b51e 100644 --- a/collections/map_keys.ts +++ b/collections/map_keys.ts @@ -8,7 +8,14 @@ * If the transformed entries contain the same key multiple times, only the last * one will appear in the returned record. * - * @example + * @template T The type of the values in the input record. + * + * @param record The record to map keys from. + * @param transformer The function to transform each key. + * + * @returns A new record with all keys transformed by the given transformer. + * + * @example Basic usage * ```ts * import { mapKeys } from "@std/collections/map-keys"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -16,7 +23,7 @@ * const counts = { a: 5, b: 3, c: 8 }; * * assertEquals( - * mapKeys(counts, (it) => it.toUpperCase()), + * mapKeys(counts, (key) => key.toUpperCase()), * { * A: 5, * B: 3, diff --git a/collections/map_not_nullish.ts b/collections/map_not_nullish.ts index fc84f02b3c21..e1047bc73120 100644 --- a/collections/map_not_nullish.ts +++ b/collections/map_not_nullish.ts @@ -6,7 +6,16 @@ * using the given transformer, except the ones that were transformed to `null` * or `undefined`. * - * @example + * @template T The type of the elements in the input array. + * @template O The type of the elements in the output array. + * + * @param array The array to map elements from. + * @param transformer The function to transform each element. + * + * @returns A new array with all elements transformed by the given transformer, + * except the ones that were transformed to `null` or `undefined`. + * + * @example Basic usage * ```ts * import { mapNotNullish } from "@std/collections/map-not-nullish"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -17,7 +26,7 @@ * { middleName: undefined }, * { middleName: "Martha" }, * ]; - * const foundMiddleNames = mapNotNullish(people, (it) => it.middleName); + * const foundMiddleNames = mapNotNullish(people, (people) => people.middleName); * * assertEquals(foundMiddleNames, ["William", "Martha"]); * ``` diff --git a/collections/map_values.ts b/collections/map_values.ts index 806d19d7b0cf..7694a993459c 100644 --- a/collections/map_values.ts +++ b/collections/map_values.ts @@ -6,22 +6,31 @@ * new record containing the resulting keys associated to the last value that * produced them. * - * @example + * @template T The type of the values in the input record. + * @template O The type of the values in the output record. + * @template K The type of the keys in the input and output records. + * + * @param record The record to map values from. + * @param transformer The function to transform each value. + * + * @returns A new record with all values transformed by the given transformer. + * + * @example Basic usage * ```ts * import { mapValues } from "@std/collections/map-values"; * import { assertEquals } from "@std/assert/assert-equals"; * * const usersById = { - * "a5ec": { name: "Mischa" }, - * "de4f": { name: "Kim" }, + * a5ec: { name: "Mischa" }, + * de4f: { name: "Kim" }, * }; - * const namesById = mapValues(usersById, (it) => it.name); + * const namesById = mapValues(usersById, (user) => user.name); * * assertEquals( * namesById, * { - * "a5ec": "Mischa", - * "de4f": "Kim", + * a5ec: "Mischa", + * de4f: "Kim", * }, * ); * ``` @@ -35,7 +44,16 @@ export function mapValues( * new record containing the resulting keys associated to the last value that * produced them. * - * @example + * @template T The type of the values in the input record. + * @template O The type of the values in the output record. + * @template K The type of the keys in the input and output records. + * + * @param record The record to map values from. + * @param transformer The function to transform each value. + * + * @returns A new record with all values transformed by the given transformer. + * + * @example Basic usage * ```ts * import { mapValues } from "@std/collections/map-values"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/max_by.ts b/collections/max_by.ts index 890fe1111f89..f00e74dffa78 100644 --- a/collections/max_by.ts +++ b/collections/max_by.ts @@ -5,7 +5,15 @@ * Returns the first element that is the largest value of the given function or * undefined if there are no elements. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the maximum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The first element that is the largest value of the given function or + * undefined if there are no elements. + * + * @example Basic usage * ```ts * import { maxBy } from "@std/collections/max-by"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -16,7 +24,7 @@ * { name: "John", age: 23 }, * ]; * - * const personWithMaxAge = maxBy(people, (i) => i.age); + * const personWithMaxAge = maxBy(people, (person) => person.age); * * assertEquals(personWithMaxAge, { name: "Kim", age: 42 }); * ``` @@ -29,9 +37,18 @@ export function maxBy( * Returns the first element that is the largest value of the given function or * undefined if there are no elements. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the maximum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The first element that is the largest value of the given function or + * undefined if there are no elements. + * + * @example Basic usage * ```ts * import { maxBy } from "@std/collections/max-by"; + * import { assertEquals } from "@std/assert/assert-equals"; * * const people = [ * { name: "Anna" }, @@ -39,7 +56,9 @@ export function maxBy( * { name: "John" }, * ]; * - * const personWithMaxName = maxBy(people, (i) => i.name); + * const personWithMaxName = maxBy(people, (person) => person.name); + * + * assertEquals(personWithMaxName, { name: "Kim" }); * ``` */ export function maxBy( @@ -50,7 +69,15 @@ export function maxBy( * Returns the first element that is the largest value of the given function or * undefined if there are no elements. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the maximum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The first element that is the largest value of the given function or + * undefined if there are no elements. + * + * @example Basic usage * ```ts * import { maxBy } from "@std/collections/max-by"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -61,7 +88,7 @@ export function maxBy( * { name: "John", age: 23n }, * ]; * - * const personWithMaxAge = maxBy(people, (i) => i.age); + * const personWithMaxAge = maxBy(people, (person) => person.age); * * assertEquals(personWithMaxAge, { name: "Kim", age: 42n }); * ``` @@ -74,9 +101,18 @@ export function maxBy( * Returns the first element that is the largest value of the given function or * undefined if there are no elements. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the maximum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The first element that is the largest value of the given function or + * undefined if there are no elements. + * + * @example Basic usage * ```ts * import { maxBy } from "@std/collections/max-by"; + * import { assertEquals } from "@std/assert/assert-equals"; * * const people = [ * { name: "Anna", startedAt: new Date("2020-01-01") }, @@ -84,7 +120,9 @@ export function maxBy( * { name: "John", startedAt: new Date("2020-03-01") }, * ]; * - * const personWithLastStartedAt = maxBy(people, (i) => i.startedAt); + * const personWithLastStartedAt = maxBy(people, (person) => person.startedAt); + * + * assertEquals(personWithLastStartedAt, { name: "Kim", startedAt: new Date("2021-03-01") }); * ``` */ export function maxBy( diff --git a/collections/max_of.ts b/collections/max_of.ts index 93927e29aa7c..037803b70920 100644 --- a/collections/max_of.ts +++ b/collections/max_of.ts @@ -4,9 +4,17 @@ /** * Applies the given selector to all elements of the provided collection and * returns the max value of all elements. If an empty array is provided the - * function will return undefined + * function will return undefined. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the maximum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The largest value of the given function or undefined if there are no + * elements. + * + * @example Basic usage * ```ts * import { maxOf } from "@std/collections/max-of"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -17,7 +25,7 @@ * { name: "tomato", count: 32 }, * ]; * - * const maxCount = maxOf(inventory, (i) => i.count); + * const maxCount = maxOf(inventory, (item) => item.count); * * assertEquals(maxCount, 32); * ``` @@ -29,9 +37,17 @@ export function maxOf( /** * Applies the given selector to all elements of the provided collection and * returns the max value of all elements. If an empty array is provided the - * function will return undefined + * function will return undefined. + * + * @template T The type of the elements in the array. + * + * @param array The array to find the maximum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The first element that is the largest value of the given function or + * undefined if there are no elements. * - * @example + * @example Basic usage * ```ts * import { maxOf } from "@std/collections/max-of"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/max_with.ts b/collections/max_with.ts index d8ccdbfb2223..f14da123e4e8 100644 --- a/collections/max_with.ts +++ b/collections/max_with.ts @@ -6,10 +6,18 @@ * comparator or undefined if there are no elements. * * The comparator is expected to work exactly like one passed to `Array.sort`, - * which means that `comparator(a, b)` should return a negative number if `a < b`, - * a positive number if `a > b` and `0` if `a === b`. + * which means that `comparator(a, b)` should return a negative number if + * `a < b`, a positive number if `a > b` and `0` if `a === b`. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the maximum element in. + * @param comparator The function to compare elements. + * + * @returns The first element that is the largest value of the given function or + * undefined if there are no elements. + * + * @example Basic usage * ```ts * import { maxWith } from "@std/collections/max-with"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/min_by.ts b/collections/min_by.ts index 03258448534f..cdebbd586b1f 100644 --- a/collections/min_by.ts +++ b/collections/min_by.ts @@ -3,9 +3,17 @@ /** * Returns the first element that is the smallest value of the given function or - * undefined if there are no elements + * undefined if there are no elements. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the minimum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The first element that is the smallest value of the given function + * or undefined if there are no elements. + * + * @example Basic usage * ```ts * import { minBy } from "@std/collections/min-by"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -27,11 +35,20 @@ export function minBy( ): T | undefined; /** * Returns the first element that is the smallest value of the given function or - * undefined if there are no elements + * undefined if there are no elements. + * + * @template T The type of the elements in the array. * - * @example + * @param array The array to find the minimum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The first element that is the smallest value of the given function + * or undefined if there are no elements. + * + * @example Basic usage * ```ts * import { minBy } from "@std/collections/min-by"; + * import { assertEquals } from "@std/assert/assert-equals"; * * const people = [ * { name: "Anna" }, @@ -39,7 +56,9 @@ export function minBy( * { name: "John" }, * ]; * - * const personWithMinName = minBy(people, (i) => i.name); + * const personWithMinName = minBy(people, (person) => person.name); + * + * assertEquals(personWithMinName, { name: "Anna" }); * ``` */ export function minBy( @@ -48,9 +67,17 @@ export function minBy( ): T | undefined; /** * Returns the first element that is the smallest value of the given function or - * undefined if there are no elements + * undefined if there are no elements. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the minimum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The first element that is the smallest value of the given function + * or undefined if there are no elements. + * + * @example Basic usage * ```ts * import { minBy } from "@std/collections/min-by"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -72,11 +99,20 @@ export function minBy( ): T | undefined; /** * Returns the first element that is the smallest value of the given function or - * undefined if there are no elements + * undefined if there are no elements. + * + * @template T The type of the elements in the array. * - * @example + * @param array The array to find the minimum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The first element that is the smallest value of the given function + * or undefined if there are no elements. + * + * @example Basic usage * ```ts * import { minBy } from "@std/collections/min-by"; + * import { assertEquals } from "@std/assert/assert-equals"; * * const people = [ * { name: "Anna", startedAt: new Date("2020-01-01") }, @@ -84,7 +120,7 @@ export function minBy( * { name: "John", startedAt: new Date("2019-01-01") }, * ]; * - * const personWithMinStartedAt = minBy(people, (i) => i.startedAt); + * const personWithMinStartedAt = minBy(people, (person) => person.startedAt); * ``` */ export function minBy( diff --git a/collections/min_of.ts b/collections/min_of.ts index 98cb8927f693..0c187d756df3 100644 --- a/collections/min_of.ts +++ b/collections/min_of.ts @@ -6,7 +6,15 @@ * returns the min value of all elements. If an empty array is provided the * function will return undefined. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the minimum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The smallest value of the given function or undefined if there are + * no elements. + * + * @example Basic usage * ```ts * import { minOf } from "@std/collections/min-of"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -16,7 +24,8 @@ * { name: "soy", count: 4 }, * { name: "tomato", count: 32 }, * ]; - * const minCount = minOf(inventory, (i) => i.count); + * + * const minCount = minOf(inventory, (item) => item.count); * * assertEquals(minCount, 2); * ``` @@ -30,7 +39,15 @@ export function minOf( * returns the min value of all elements. If an empty array is provided the * function will return undefined. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the minimum element in. + * @param selector The function to get the value to compare from each element. + * + * @returns The first element that is the smallest value of the given function + * or undefined if there are no elements. + * + * @example Basic usage * ```ts * import { minOf } from "@std/collections/min-of"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -40,7 +57,8 @@ export function minOf( * { name: "soy", count: 4n }, * { name: "tomato", count: 32n }, * ]; - * const minCount = minOf(inventory, (i) => i.count); + * + * const minCount = minOf(inventory, (item) => item.count); * * assertEquals(minCount, 2n); * ``` diff --git a/collections/min_with.ts b/collections/min_with.ts index fb4f7eb23e36..6453e5f81187 100644 --- a/collections/min_with.ts +++ b/collections/min_with.ts @@ -3,9 +3,17 @@ /** * Returns the first element having the smallest value according to the provided - * comparator or undefined if there are no elements + * comparator or undefined if there are no elements. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to find the minimum element in. + * @param comparator The function to compare elements. + * + * @returns The first element that is the smallest value of the given function + * or undefined if there are no elements. + * + * @example Basic usage * ```ts * import { minWith } from "@std/collections/min-with"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/omit.ts b/collections/omit.ts index 687b22d7d428..dafb01af5e97 100644 --- a/collections/omit.ts +++ b/collections/omit.ts @@ -4,7 +4,15 @@ /** * Creates a new object by excluding the specified keys from the provided object. * - * @example + * @template T The type of the object. + * @template K The type of the keys to omit. + * + * @param obj The object to omit keys from. + * @param keys The keys to omit from the object. + * + * @returns A new object with the specified keys omitted. + * + * @example Basic usage * ```ts * import { omit } from "@std/collections/omit"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/partition.ts b/collections/partition.ts index e471c22c46d2..3f91d6953bf6 100644 --- a/collections/partition.ts +++ b/collections/partition.ts @@ -6,7 +6,16 @@ * the given array that match the given predicate and the second one containing * all that do not. * - * @example + * @template T The type of the elements in the array. + * + * @param array The array to partition. + * @param predicate The predicate function to determine which array an element + * belongs to. + * + * @returns A tuple of two arrays. The first array contains all elements that + * match the predicate, the second contains all elements that do not. + * + * @example Basic usage * ```ts * import { partition } from "@std/collections/partition"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -27,7 +36,21 @@ export function partition( * the given array that match the given predicate and the second one containing * all that do not. * - * @example + * This version of the function is a type-guard version of the function. It + * allows you to specify a type-guard predicate function that narrows the type + * of the elements in the array. + * + * @template T The type of the elements in the array. + * @template U The type of the elements that match the predicate. + * + * @param array The array to partition. + * @param predicate The type-guard predicate function to determine which array + * an element belongs to. + * + * @returns A tuple of two arrays. The first array contains all elements that + * match the predicate, the second contains all elements that do not. + * + * @example Basic usage * ```ts * import { partition } from "@std/collections/partition"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/partition_entries.ts b/collections/partition_entries.ts index 86292a0ee422..f039e7f67198 100644 --- a/collections/partition_entries.ts +++ b/collections/partition_entries.ts @@ -6,16 +6,24 @@ * the given record that match the given predicate and the second one containing * all that do not. * - * @example + * @template T The type of the values in the record. + * + * @param record The record to partition. + * @param predicate The predicate function to determine which entries go where. + * + * @returns A tuple containing two records, the first one containing all entries + * that match the predicate and the second one containing all that do not. + * + * @example Basic usage * ```ts * import { partitionEntries } from "@std/collections/partition-entries"; * import { assertEquals } from "@std/assert/assert-equals"; * * const menu = { - * "Salad": 11, - * "Soup": 8, - * "Pasta": 13, - * } as const; + * Salad: 11, + * Soup: 8, + * Pasta: 13, + * }; * const myOptions = partitionEntries( * menu, * ([item, price]) => item !== "Pasta" && price < 10, @@ -24,8 +32,8 @@ * assertEquals( * myOptions, * [ - * { "Soup": 8 }, - * { "Salad": 11, "Pasta": 13 }, + * { Soup: 8 }, + * { Salad: 11, Pasta: 13 }, * ], * ); * ``` diff --git a/collections/permutations.ts b/collections/permutations.ts index b9ad9c18129d..4f5d37439d7a 100644 --- a/collections/permutations.ts +++ b/collections/permutations.ts @@ -6,7 +6,13 @@ * Ignores equality of elements, meaning this will always return the same * number of permutations for a given length of input. * - * @example + * @template T The type of the elements in the array. + * + * @param inputArray The array to build permutations from. + * + * @returns An array of all possible permutations of the given array. + * + * @example Basic usage * ```ts * import { permutations } from "@std/collections/permutations"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/pick.ts b/collections/pick.ts index effb223e3dc6..e3bd03faf546 100644 --- a/collections/pick.ts +++ b/collections/pick.ts @@ -2,9 +2,18 @@ // This module is browser compatible. /** - * Creates a new object by including the specified keys from the provided object. + * Creates a new object by including the specified keys from the provided + * object. * - * @example + * @template T The type of the object. + * @template K The type of the keys. + * + * @param obj The object to pick keys from. + * @param keys The keys to include in the new object. + * + * @returns A new object with the specified keys from the provided object. + * + * @example Basic usage * ```ts * import { pick } from "@std/collections/pick"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/reduce_groups.ts b/collections/reduce_groups.ts index 8db8df345fc4..1c7a2aee16e5 100644 --- a/collections/reduce_groups.ts +++ b/collections/reduce_groups.ts @@ -8,22 +8,28 @@ import { mapValues } from "./map_values.ts"; * results together with the respective group keys. * * @template T input type of an item in a group in the given grouping. - * @template A type of the accumulator value, which will match the returned record's values. - * @example + * @template A type of the accumulator value, which will match the returned + * record's values. + * + * @param record The grouping to reduce. + * @param reducer The reducer function to apply to each group. + * @param initialValue The initial value of the accumulator. + * + * @example Basic usage * ```ts * import { reduceGroups } from "@std/collections/reduce-groups"; * import { assertEquals } from "@std/assert/assert-equals"; * * const votes = { - * "Woody": [2, 3, 1, 4], - * "Buzz": [5, 9], + * Woody: [2, 3, 1, 4], + * Buzz: [5, 9], * }; * - * const totalVotes = reduceGroups(votes, (sum, it) => sum + it, 0); + * const totalVotes = reduceGroups(votes, (sum, vote) => sum + vote, 0); * * assertEquals(totalVotes, { - * "Woody": 10, - * "Buzz": 14, + * Woody: 10, + * Buzz: 14, * }); * ``` */ diff --git a/collections/running_reduce.ts b/collections/running_reduce.ts index d828bf6212b7..894a5d4cc189 100644 --- a/collections/running_reduce.ts +++ b/collections/running_reduce.ts @@ -6,7 +6,14 @@ * result as the accumulator to the next respective call, starting with the * given initialValue. Returns all intermediate accumulator results. * - * @example + * @template T The type of the elements in the array. + * @template O The type of the accumulator. + * + * @param array The array to reduce. + * @param reducer The reducer function to apply to each element. + * @param initialValue The initial value of the accumulator. + * + * @example Basic usage * ```ts * import { runningReduce } from "@std/collections/running-reduce"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/sample.ts b/collections/sample.ts index ac3b643c4f13..61f5c609ba17 100644 --- a/collections/sample.ts +++ b/collections/sample.ts @@ -6,7 +6,15 @@ import { randomInteger } from "./_utils.ts"; /** * Returns a random element from the given array. * - * @example + * @template T The type of the elements in the array. + * @template O The type of the accumulator. + * + * @param array The array to sample from. + * + * @returns A random element from the given array, or `undefined` if the array + * is empty. + * + * @example Basic usage * ```ts * import { sample } from "@std/collections/sample"; * import { assert } from "@std/assert/assert"; @@ -14,7 +22,7 @@ import { randomInteger } from "./_utils.ts"; * const numbers = [1, 2, 3, 4]; * const random = sample(numbers); * - * assert(numbers.includes(random as number)); + * assert(numbers.includes(random!)); * ``` */ export function sample(array: readonly T[]): T | undefined { diff --git a/collections/sliding_windows.ts b/collections/sliding_windows.ts index c0f7b705487a..d2af1bc58026 100644 --- a/collections/sliding_windows.ts +++ b/collections/sliding_windows.ts @@ -1,6 +1,24 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. // This module is browser compatible. +/** Options for {@linkcode slidingWindows}. */ +export interface SlidingWindowsOptions { + /** + * If step is set, each window will start that many elements after the last + * window's start. + * + * @default {1} + */ + step?: number; + /** + * If partial is set, windows will be generated for the last elements of the + * collection, resulting in some undefined values if size is greater than 1. + * + * @default {false} + */ + partial?: boolean; +} + /** * Generates sliding views of the given array of the given size and returns a * new array containing all of them. @@ -11,7 +29,15 @@ * If partial is set, windows will be generated for the last elements of the * collection, resulting in some undefined values if size is greater than 1. * - * @example + * @template T The type of the array elements. + * + * @param array The array to generate sliding windows from. + * @param size The size of the sliding windows. + * @param options The options for generating sliding windows. + * + * @returns A new array containing all sliding windows of the given size. + * + * @example Usage * ```ts * import { slidingWindows } from "@std/collections/sliding-windows"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -43,35 +69,18 @@ export function slidingWindows( array: readonly T[], size: number, - { step = 1, partial = false }: { - /** - * If step is set, each window will start that many elements after the last - * window's start. - * - * @default {1} - */ - step?: number; - /** - * If partial is set, windows will be generated for the last elements of the - * collection, resulting in some undefined values if size is greater than 1. - * - * @default {false} - */ - partial?: boolean; - } = {}, + options: SlidingWindowsOptions = {}, ): T[][] { + const { step = 1, partial = false } = options; + if ( !Number.isInteger(size) || !Number.isInteger(step) || size <= 0 || step <= 0 ) { throw new RangeError("Both size and step must be positive integer."); } - /** length of the return array */ - const length = Math.floor((array.length - (partial ? 1 : size)) / step + 1); - - const result = []; - for (let i = 0; i < length; i++) { - result.push(array.slice(i * step, i * step + size)); - } - return result; + return Array.from( + { length: Math.floor((array.length - (partial ? 1 : size)) / step + 1) }, + (_, i) => array.slice(i * step, i * step + size), + ); } diff --git a/collections/sort_by.ts b/collections/sort_by.ts index 2add9c69a6fc..24779506a0c5 100644 --- a/collections/sort_by.ts +++ b/collections/sort_by.ts @@ -6,15 +6,29 @@ export type Order = "asc" | "desc"; /** Options for {@linkcode sortBy}. */ export type SortByOptions = { + /** + * The order to sort the elements in. + * + * @default {"asc"} + */ order: Order; }; /** * Returns all elements in the given collection, sorted by their result using * the given selector. The selector function is called only once for each - * element. Ascending or descending order can be specified. + * element. Ascending or descending order can be specified through the `order` + * option. By default, the elements are sorted in ascending order. * - * @example + * @template T The type of the array elements. + * + * @param array The array to sort. + * @param selector The selector function to get the value to sort by. + * @param options The options for sorting. + * + * @returns A new array containing all elements sorted by the selector. + * + * @example Usage * ```ts * import { sortBy } from "@std/collections/sort-by"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -24,7 +38,7 @@ export type SortByOptions = { * { name: "Kim", age: 42 }, * { name: "John", age: 23 }, * ]; - * const sortedByAge = sortBy(people, (it) => it.age); + * const sortedByAge = sortBy(people, (person) => person.age); * * assertEquals(sortedByAge, [ * { name: "John", age: 23 }, @@ -32,7 +46,7 @@ export type SortByOptions = { * { name: "Kim", age: 42 }, * ]); * - * const sortedByAgeDesc = sortBy(people, (it) => it.age, { order: "desc" }); + * const sortedByAgeDesc = sortBy(people, (person) => person.age, { order: "desc" }); * * assertEquals(sortedByAgeDesc, [ * { name: "Kim", age: 42 }, @@ -49,9 +63,18 @@ export function sortBy( /** * Returns all elements in the given collection, sorted by their result using * the given selector. The selector function is called only once for each - * element. Ascending or descending order can be specified. + * element. Ascending or descending order can be specified through the `order` + * option. By default, the elements are sorted in ascending order. + * + * @template T The type of the array elements. * - * @example + * @param array The array to sort. + * @param selector The selector function to get the value to sort by. + * @param options The options for sorting. + * + * @returns A new array containing all elements sorted by the selector. + * + * @example Usage * ```ts * import { sortBy } from "@std/collections/sort-by"; * @@ -61,6 +84,7 @@ export function sortBy( * { name: "John" }, * ]; * const sortedByName = sortBy(people, (it) => it.name); + * ``` */ export function sortBy( array: readonly T[], @@ -70,18 +94,35 @@ export function sortBy( /** * Returns all elements in the given collection, sorted by their result using * the given selector. The selector function is called only once for each - * element. Ascending or descending order can be specified. + * element. Ascending or descending order can be specified through the `order` + * option. By default, the elements are sorted in ascending order. * - * @example + * @template T The type of the array elements. + * + * @param array The array to sort. + * @param selector The selector function to get the value to sort by. + * @param options The options for sorting. + * + * @returns A new array containing all elements sorted by the selector. + * + * @example Usage * ```ts * import { sortBy } from "@std/collections/sort-by"; + * import { assertEquals } from "@std/assert/assert-equals"; * * const people = [ * { name: "Anna", age: 34n }, * { name: "Kim", age: 42n }, * { name: "John", age: 23n }, * ]; - * const sortedByAge = sortBy(people, (it) => it.age); + * + * const sortedByAge = sortBy(people, (person) => person.age); + * + * assertEquals(sortedByAge, [ + * { name: "John", age: 23n }, + * { name: "Anna", age: 34n }, + * { name: "Kim", age: 42n }, + * ]); * ``` */ @@ -93,18 +134,35 @@ export function sortBy( /** * Returns all elements in the given collection, sorted by their result using * the given selector. The selector function is called only once for each - * element. Ascending or descending order can be specified. + * element. Ascending or descending order can be specified through the `order` + * option. By default, the elements are sorted in ascending order. + * + * @template T The type of the array elements. + * + * @param array The array to sort. + * @param selector The selector function to get the value to sort by. + * @param options The options for sorting. + * + * @returns A new array containing all elements sorted by the selector. * - * @example + * @example Usage * ```ts * import { sortBy } from "@std/collections/sort-by"; + * import { assertEquals } from "@std/assert/assert-equals"; * * const people = [ * { name: "Anna", startedAt: new Date("2020-01-01") }, * { name: "Kim", startedAt: new Date("2020-03-01") }, * { name: "John", startedAt: new Date("2020-06-01") }, * ]; - * const sortedByStartedAt = sortBy(people, (it) => it.startedAt); + * + * const sortedByStartedAt = sortBy(people, (people) => people.startedAt); + * + * assertEquals(sortedByStartedAt, [ + * { name: "Anna", startedAt: new Date("2020-01-01") }, + * { name: "Kim", startedAt: new Date("2020-03-01") }, + * { name: "John", startedAt: new Date("2020-06-01") }, + * ]); * ``` */ export function sortBy( diff --git a/collections/sum_of.ts b/collections/sum_of.ts index 748ca2b16ffd..2b9753be38c1 100644 --- a/collections/sum_of.ts +++ b/collections/sum_of.ts @@ -5,7 +5,14 @@ * Applies the given selector to all elements in the given collection and * calculates the sum of the results. * - * @example + * @template T The type of the array elements. + * + * @param array The array to calculate the sum of. + * @param selector The selector function to get the value to sum. + * + * @returns The sum of all elements in the collection. + * + * @example Basic usage * ```ts * import { sumOf } from "@std/collections/sum-of"; * import { assertEquals } from "@std/assert/assert-equals"; @@ -15,7 +22,8 @@ * { name: "Kim", age: 42 }, * { name: "John", age: 23 }, * ]; - * const totalAge = sumOf(people, (i) => i.age); + * + * const totalAge = sumOf(people, (person) => person.age); * * assertEquals(totalAge, 99); * ``` diff --git a/collections/take_last_while.ts b/collections/take_last_while.ts index 9a793757ef33..e64bb9471845 100644 --- a/collections/take_last_while.ts +++ b/collections/take_last_while.ts @@ -5,17 +5,25 @@ * Returns all elements in the given array after the last element that does not * match the given predicate. * - * @example + * @template T The type of the array elements. + * + * @param array The array to take elements from. + * @param predicate The predicate function to determine if an element should be + * included. + * + * @returns A new array containing all elements after the last element that does + * not match the predicate. + * + * @example Basic usage * ```ts * import { takeLastWhile } from "@std/collections/take-last-while"; * import { assertEquals } from "@std/assert/assert-equals"; * - * const arr = [1, 2, 3, 4, 5, 6]; + * const numbers = [1, 2, 3, 4, 5, 6]; + * + * const result = takeLastWhile(numbers, (number) => number > 4); * - * assertEquals( - * takeLastWhile(arr, (i) => i > 4), - * [5, 6], - * ); + * assertEquals(result, [5, 6]); * ``` */ export function takeLastWhile( diff --git a/collections/take_while.ts b/collections/take_while.ts index 2b61d9846661..244a6a788336 100644 --- a/collections/take_while.ts +++ b/collections/take_while.ts @@ -5,17 +5,25 @@ * Returns all elements in the given collection until the first element that * does not match the given predicate. * - * @example + * @template T The type of the array elements. + * + * @param array The array to take elements from. + * @param predicate The predicate function to determine if an element should be + * included. + * + * @returns A new array containing all elements until the first element that + * does not match the predicate. + * + * @example Basic usage * ```ts * import { takeWhile } from "@std/collections/take-while"; * import { assertEquals } from "@std/assert/assert-equals"; * - * const arr = [1, 2, 3, 4, 5, 6]; + * const numbers = [1, 2, 3, 4, 5, 6]; + * + * const result = takeWhile(numbers, (number) => number < 4); * - * assertEquals( - * takeWhile(arr, (i) => i !== 4), - * [1, 2, 3], - * ); + * assertEquals(result, [1, 2, 3]); * ``` */ export function takeWhile( diff --git a/collections/union.ts b/collections/union.ts index 4ad44a9f860a..ddf7d4f63b57 100644 --- a/collections/union.ts +++ b/collections/union.ts @@ -4,13 +4,20 @@ /** * Returns all distinct elements that appear in any of the given arrays. * - * @example + * @template T The type of the array elements. + * + * @param arrays The arrays to get the union of. + * + * @returns A new array containing all distinct elements from the given arrays. + * + * @example Basic usage * ```ts * import { union } from "@std/collections/union"; * import { assertEquals } from "@std/assert/assert-equals"; * * const soupIngredients = ["Pepper", "Carrots", "Leek"]; * const saladIngredients = ["Carrots", "Radicchio", "Pepper"]; + * * const shoppingList = union(soupIngredients, saladIngredients); * * assertEquals(shoppingList, ["Pepper", "Carrots", "Leek", "Radicchio"]); diff --git a/collections/unzip.ts b/collections/unzip.ts index adec3ed8f0e8..0cb109f5a1df 100644 --- a/collections/unzip.ts +++ b/collections/unzip.ts @@ -6,6 +6,15 @@ * returned array holding all first tuple elements and the second one holding * all the second elements. * + * @template T The type of the first tuple elements. + * @template U The type of the second tuple elements. + * + * @param pairs The array of 2-tuples to unzip. + * + * @returns A tuple containing two arrays, the first one holding all first tuple + * elements and the second one holding all second elements. + * + * @example Basic usage * ```ts * import { unzip } from "@std/collections/unzip"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/without_all.ts b/collections/without_all.ts index 645db2cd0b57..12cdf537d21f 100644 --- a/collections/without_all.ts +++ b/collections/without_all.ts @@ -4,7 +4,15 @@ /** * Returns an array excluding all given values. * - * @example + * @template T The type of the array elements. + * + * @param array The array to exclude values from. + * @param values The values to exclude from the array. + * + * @returns A new array containing all elements from the given array except the + * ones that are in the values array. + * + * @example Basic usage * ```ts * import { withoutAll } from "@std/collections/without-all"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/collections/zip.ts b/collections/zip.ts index 5419283a7346..28b1b82944d1 100644 --- a/collections/zip.ts +++ b/collections/zip.ts @@ -8,7 +8,12 @@ import { minOf } from "./min_of.ts"; * stopping when the smallest array's end is reached. * * @template T the type of the tuples produced by this function. - * @example + * + * @param arrays The arrays to zip. + * + * @returns A new array containing N-tuples of elements from the given arrays. + * + * @example Basic usage * ```ts * import { zip } from "@std/collections/zip"; * import { assertEquals } from "@std/assert/assert-equals"; diff --git a/deno.json b/deno.json index 435605e06852..6bdc0c1e7c69 100644 --- a/deno.json +++ b/deno.json @@ -19,7 +19,7 @@ "lint:circular": "deno run --allow-env --allow-read --allow-net=deno.land,jsr.io ./_tools/check_circular_package_dependencies.ts", "lint:mod-exports": "deno run --allow-env --allow-read ./_tools/check_mod_exports.ts", "lint:tools-types": "deno check _tools/*.ts", - "lint:docs": "deno run -A _tools/check_docs.ts && deno doc --lint bytes/mod.ts datetime/mod.ts url/mod.ts", + "lint:docs": "deno run -A _tools/check_docs.ts && deno doc --lint collections/mod.ts bytes/mod.ts datetime/mod.ts url/mod.ts", "lint": "deno lint && deno task fmt:licence-headers --check && deno task lint:circular && deno task lint:deprecations && deno task lint:tools-types && deno task lint:mod-exports && deno task lint:docs", "typos": "typos -c ./.github/workflows/typos.toml", "build:crypto": "deno task --cwd crypto/_wasm wasmbuild",