Skip to content

Instantly share code, notes, and snippets.

@wmeints
Last active December 29, 2016 14:25
Show Gist options
  • Save wmeints/906117e7d4ef9257236950c84da40a10 to your computer and use it in GitHub Desktop.
Save wmeints/906117e7d4ef9257236950c84da40a10 to your computer and use it in GitHub Desktop.
Converter functions for mapping object values
export type MappingRule = (data: any) => any;
export type MappingRules<T> = { [P in keyof T]?: MappingRule };
export type MapperFunction<T> = (input: T) => any;
// Maps property values based on rules that you supplied.
// Properties for which no rule was supplied are copied to the output.
// NOTICE: This mapper function does not support renaming properties.
export function mapObject<T>(input: T, rules: MappingRules<T>): any {
if(input === undefined || input === null) {
return input;
}
let result: any = {};
for(let key in input) {
if(input.hasOwnProperty(key)) {
if(input[key] === undefined || input[key] === null) {
result[key] = input[key];
} else if(rules[key]) {
result[key] = rules[key](input[key]);
} else {
result[key] = input[key];
}
}
}
return result;
}
// Generates a mapping function that converts property values based on rules.
export function mapper<T>(rules: MappingRules<T>): MapperFunction<T> {
return (data) => mapObject(data, rules);
}
// Generates a mapping function that maps an array of objects
export function collectionMapper<T>(rules: MappingRules<T>): MapperFunction<T[]> {
return (data) => data.map(item => mapObject(item, rules));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment