Last active
November 6, 2022 11:13
-
-
Save ajsaraujo/9d5d5271565b65a6b25fdafeb24ee7d4 to your computer and use it in GitHub Desktop.
Sum an array of numbers or objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Got the
KeysMatchingType
from this StackOverflow thread.