Skip to content

Instantly share code, notes, and snippets.

@jessycormier
Created November 17, 2018 00:16
Show Gist options
  • Save jessycormier/a1b56dfad8c86ac67a9335ac6d052269 to your computer and use it in GitHub Desktop.
Save jessycormier/a1b56dfad8c86ac67a9335ac6d052269 to your computer and use it in GitHub Desktop.
Object transformer
import { Injectable } from '@angular/core';
type Checker = (any: any) => boolean;
type Transformer = (any: any) => any;
@Injectable()
export class ObjectTransformerService {
/**
* process data and transform it.
* @description Checker and transformer are passed the value currently being evaluated, if the
* checker returns a value of true the transformer will be called otherwise the code will continue processing. The
* value the transformer returns will become the property otherwise the original property value will remain.
* @param data can be a complex object with values, arrays and objects, array, or a primitive value.
* @param checker receives the property/value being looped over for you to perform your logic check. Return should be a boolean.
* @param transformer receives the property/value being looped over for transformation. Return will become the property/value
* @returns the transformed data or original data passed it if no transformation
*/
public process(data: any, checker: Checker, transformer: Transformer) {
if (checker(data)) {
return transformer(data);
}
if (Array.isArray(data)) {
const array: any[] = [];
(<any[]>data).forEach((item, index) => {
array.push(this.process(item, checker, transformer));
});
return array;
}
if (typeof data === 'object') {
const newObj = {};
Object.entries(data).forEach(([key, value]) => {
newObj[key] = value;
if (checker(value)) {
newObj[key] = transformer(value);
}
if (value !== null && typeof value === 'object') {
newObj[key] = this.process(value, checker, transformer);
}
});
return newObj;
}
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment