Skip to content

Instantly share code, notes, and snippets.

@AyAyEm
Created April 13, 2021 20:29
Show Gist options
  • Save AyAyEm/4c7d54a902dad6a2c2c05d0fd48d3891 to your computer and use it in GitHub Desktop.
Save AyAyEm/4c7d54a902dad6a2c2c05d0fd48d3891 to your computer and use it in GitHub Desktop.
Sum with variable args from just numbers to arrays of arrays of numbers
type Sum<T> = Array<T> | Array<Sum<T>>
function sum<T extends number>(...list: Sum<T>): number {
const innerSum = (a: number, b: number | Array<number>) => (
a + (b instanceof Array ? sum(...b) : b));
return (list as number[]).reduce(innerSum, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment