Skip to content

Instantly share code, notes, and snippets.

@vcardins
Last active March 30, 2020 22:04
Show Gist options
  • Save vcardins/fd0fb1c71fce4e5164f3b03b8f1261a2 to your computer and use it in GitHub Desktop.
Save vcardins/fd0fb1c71fce4e5164f3b03b8f1261a2 to your computer and use it in GitHub Desktop.
AutoMapper
// 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