Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | 1x 46x 46x 46x 46x 40x 113x 101x 40x 4x 2x 2x 2x 2x 4x 40x 46x | /** * Options for {@link lookAhead} operations. * @typeParam T - The type of the items in the sequence. * @group Array * @category Iteration */ export type LookAheadOptions<T> = | { /** * Specifies the last item in the sequence. */ last: T; } | { /** * Determines whether the look-ahead should wrap around to the beginning when reaching the end. */ wrapAround: boolean; }; /** * Generates pairs of consecutive elements from the input array, with optional handling for the last * element. * @typeParam T - The type of elements in the input array. * @param array - The array to iterate over. * @param options - Optional configuration for handling the last element. * @returns A generator yielding a tuple containing each element, the next element in the sequence, * and the index of the element within the sequence. Optionally, a tuple is generated for the last * element as specified by options. * @example * ```typescript * // Basic usage * const arr = [1, 2, 3]; * for (const [current, next] of lookAhead(arr)) { * console.log(current, next); * } * // [1, 2], [2, 3] * * // With wrapAround * for (const [current, next] of lookAhead(arr, { wrapAround: true })) { * console.log(current, next); * } * // [1, 2], [2, 3], [3, 1] * ``` * * With last * ```typescript * for (const [current, next] of lookAhead(arr, { last: 0 })) { * console.log(current, next); * } * // [1, 2], [2, 3], [3, 0] * ``` * @group Array * @category Iteration */ export function* lookAhead<T>( array: T[], options?: LookAheadOptions<T>, ): Generator<[T, T, number]> { if (array.length > 0) { for (let i = 0; i < array.length - 1; ++i) { yield [array[i], array[i + 1], i]; } if (options) { if ('last' in options) { yield [array.at(-1)!, options.last, array.length - 1]; } else if (options.wrapAround) { yield [array.at(-1)!, array.at(0)!, array.length - 1]; } } } } |