radash icon indicating copy to clipboard operation
radash copied to clipboard

[Request] Loosen the type on the Array sum function

Open dyerw opened this issue 1 year ago • 2 comments

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

https://github.com/sodiray/radash/blob/069b26cdd7d62e6ac16a0ad3baa1c9abcca420bc/src/array.ts#L100

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)

dyerw avatar Jul 26 '24 14:07 dyerw

@dyerw You could choose to use radashi which is a fork of radash and in it we fixed this problem

MarlonPassos-git avatar Aug 07 '24 01:08 MarlonPassos-git

Hey @dyerw, as Marlon said, this issue is fixed in radashi@beta (stable release coming very soon). If you'd like to know how Radashi (the fork) is different from Radash, I recently wrote a little bit about that: https://github.com/radashi-org/radashi/issues/168#issuecomment-2289516778

aleclarson avatar Aug 14 '24 21:08 aleclarson