Last active
March 30, 2020 22:04
-
-
Save vcardins/fd0fb1c71fce4e5164f3b03b8f1261a2 to your computer and use it in GitHub Desktop.
AutoMapper
This file contains hidden or 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
// usage: AutoMapper.map<UserProfile>(user, user.profile); | |
export class AutoMapper { | |
static map<TSource>(sourceObj: TSource, ...args: any[]): void { | |
const initializers = args.filter(Boolean) | |
if (!initializers?.length) { | |
return; | |
} | |
const sourceObjectProps = Object.getOwnPropertyNames(sourceObj); | |
const newValues = initializers.reduce((result, arg) => { | |
const argKeys = Object.getOwnPropertyNames(arg); | |
argKeys.forEach((aKey) => { | |
if (sourceObjectProps.includes(aKey)) { | |
result[aKey] = arg[aKey]; | |
} | |
}); | |
return result; | |
}, sourceObj); | |
Object.assign(sourceObj, newValues); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment