import * as Obj from './Obj'; import * as Type from './Type'; type MergeStrategy = (old: any, nu: any) => any; interface DeepMergeFunc { (a: A, b: B): A & B; (a: A, b: B, c: C): A & B & C; (a: A, b: B, c: C, d: D): A & B & C & D; (a: A, b: B, c: C, d: D, e: E): A & B & C & D & E; (a: A, b: B, c: C, d: D, e: E, f: F): A & B & C & D & E & F; (...objs: Array>): Record; } type MergeOptional = A extends undefined ? B : Exclude; type ShallowMerge = ({ [K in keyof A]: K extends keyof B ? MergeOptional : A[K] } & B); interface ShallowMergeFunc { (a: A, b: B): ShallowMerge; (a: A, b: B, c: C): ShallowMerge, C>; (a: A, b: B, c: C, d: D): ShallowMerge, C>, D>; (a: A, b: B, c: C, d: D, e: E): ShallowMerge, C>, D>, E>; (a: A, b: B, c: C, d: D, e: E, f: F): ShallowMerge, C>, D>, E>, F>; (...objs: Array>): Record; } const shallow = (old: Record, nu: Record) => { return nu; }; const deep = (old: Record, nu: Record) => { const bothObjects = Type.isPlainObject(old) && Type.isPlainObject(nu); return bothObjects ? deepMerge(old, nu) : nu; }; const baseMerge = (merger: MergeStrategy): (...objs: Array>) => any => { return (...objects: any[]) => { if (objects.length === 0) { throw new Error(`Can't merge zero objects`); } const ret: Record = {}; for (let j = 0; j < objects.length; j++) { const curObject = objects[j]; for (const key in curObject) { if (Obj.has(curObject, key)) { ret[key] = merger(ret[key], curObject[key]); } } } return ret; }; }; export const deepMerge: DeepMergeFunc = baseMerge(deep); export const merge: ShallowMergeFunc = baseMerge(shallow);