Skip to content

[Request] Loosen the type on the Array sum function #419

@dyerw

Description

@dyerw

I don't see any reason why in sum the type param T has to extend object for the non-number case:

export function sum<T extends object>(

export function sum<T extends object>(
  array: readonly T[],
  fn: (item: T) => number
): number

so long as I can provide fn: (item: T) => number what does it matter that T extends object?

My specific use case is I have a normalized data object mapping ids to objects and I want to sum a list of ids like:

const lookup: Record<string, Data> = {...};

const ids: string[] = [...];

_.sum(ids, (id) => lookup[id].numberField);

Now I could map to objects first sure, but arguably I could want to sum the length of an array of strings, or say the number of trues in a list of booleans like _.sum(listOfBools, (b) => b ? 1 : 0)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions