Skip to content

Instantly share code, notes, and snippets.

@ababup1192
Created June 14, 2019 19:22
Show Gist options
  • Save ababup1192/fdf52aa39bc77fddc7ea00605b333654 to your computer and use it in GitHub Desktop.
Save ababup1192/fdf52aa39bc77fddc7ea00605b333654 to your computer and use it in GitHub Desktop.
type A = { v1: number, v2: number };
type X<K1 extends keyof any, K2 extends keyof any> = {
[key in K1]: A | {
[key in K2]: A
}[]
}
const f = <K1 extends keyof any, K2 extends keyof any>(
obj: X<K1, K2>
): number => {
return Object.keys(obj).reduce((acc: number, key: string) => {
const item = obj[key];
return (item['v1'] != undefined && item['v2'] != undefined) ?
acc + culcA(item as A) :
acc + f(item as any);
}, 0);
}
const culcA = (a: A): number => a.v1 + a.v2;
const res =
f({ a: { v1: 1, v2: 2 }, b: [{ c: { v1: 3, v2: 4 } }, { c: { v1: 5, v2: 6} }], d: { v1: 7, v2: 8 } });
console.log(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment