Skip to content

@std/collections zip with customizable handling of where to truncate (longest vs shortest) #6732

Open
@lionel-rowe

Description

@lionel-rowe

Is your feature request related to a problem? Please describe.

Sometimes it's useful to zip arrays together without truncating the shorter ones, instead filling with undefined.

Describe the solution you'd like

Allow passing an option such as options.truncate = 'longest' to continue zipping until the longest array ends, filling missing values with undefined.

Describe alternatives you've considered

Not really sure how best to add this to the current function signature, given the variadic ...arrays param.

One possible option would be taking options as an initial parameter, which could be detected at runtime with Array.isArray:

type ZipOptions = {
  truncate?: 'shortest' | 'longest';
}

export function zip<T extends unknown[], O extends ZipOptions>(
  options: O,
  ...arrays: { [K in keyof T]: ReadonlyArray<T[K]> }
): {
  [K in keyof T]: O extends { truncate: "longest" } ? T[K] | undefined : T[K];
}[];
export function zip<T extends unknown[]>(
  ...arrays: { [K in keyof T]: ReadonlyArray<T[K]> }
): T[];
export function zip(
  ...args: unknown[]
): unknown[] {
  const [options, arrays] = args.length === 0 || Array.isArray(args[0]) ?
    [{}, args as unknown[][]] :
    [args[0] as ZipOptions, args.slice(1) as unknown[][]];

Otherwise, it might need to be a separate zipWithOptions function.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions