Skip to content

Instantly share code, notes, and snippets.

@ajsaraujo
Last active November 6, 2022 11:13
Show Gist options
  • Save ajsaraujo/9d5d5271565b65a6b25fdafeb24ee7d4 to your computer and use it in GitHub Desktop.
Save ajsaraujo/9d5d5271565b65a6b25fdafeb24ee7d4 to your computer and use it in GitHub Desktop.
Sum an array of numbers or objects
type KeysMatchingType<T, U> = NonNullable<{
[K in keyof T]: [U] extends [T[K]] ? T[K] extends U ? K : never : never;
}[keyof T]>;
function sum(values: number[]): number;
function sum<T>(values: T[], prop: KeysMatchingType<T, number>): number;
function sum<T>(values: T[], prop?: KeysMatchingType<T, number>): number {
if (values.length === 0) {
return 0;
}
const numberArray = typeof values[0] === 'number' ?
(values as number[]) :
values.map(obj => +obj[prop as keyof T]);
return numberArray.reduce((acc, curr) => acc + curr, 0);
}
@ajsaraujo
Copy link
Author

Got the KeysMatchingType from this StackOverflow thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment