Separate Utils helper methods

This commit is contained in:
Thomas Rittson 2022-06-24 10:11:59 +10:00
parent 4ecc522102
commit 3d240c05ce
2 changed files with 21 additions and 18 deletions

View File

@ -71,7 +71,7 @@ describe("Utils Service", () => {
});
});
describe("copyProperties", () => {
describe("copyToObject", () => {
const source = {
sourceProp1: "value1",
sourceProp2: "value2",
@ -81,15 +81,13 @@ describe("Utils Service", () => {
it("Copies properties with different target names", () => {
const map = {
sourceProp1: "targetProp1",
sourceProp2: "targetProp2",
sourceProp3: "targetProp3",
};
const target = Utils.copyToNewObject(source, map);
const target = Utils.copyToObject(source, map, {});
expect(target).toEqual({
targetProp1: "value1",
targetProp2: "value2",
targetProp3: "value3",
});
});
@ -97,25 +95,23 @@ describe("Utils Service", () => {
it("Copies properties with the same names", () => {
const map: any = {
sourceProp1: null,
sourceProp2: null,
sourceProp3: null,
};
const target = Utils.copyToNewObject(source, map);
const target = Utils.copyToObject(source, map, {});
expect(target).toEqual(source);
expect(target).toEqual({
sourceProp1: "value1",
sourceProp3: "value3",
});
});
});
describe("CopyToNewObject", () => {
it("Instantiates a new object type if provided", () => {
class TestClass {
prop1: string;
}
class TestClass {}
const map: any = {
sourceProp1: "prop1",
};
const target = Utils.copyToNewObject(source, map, TestClass);
const target = Utils.copyToNewObject({}, {}, TestClass);
expect(target).toBeInstanceOf(TestClass);
});

View File

@ -350,9 +350,7 @@ export class Utils {
/**
* Copies properties from a source object to a new object according to a mapping
* @param source The source object to copy from
* @param map A map of source:target property names (leave target null to use the same property name as source)
* @param targetType The target type to be created and populated (leave null to use a plain JS object)
* Same as Utils.copyToObject but will instantiate the new object for you according to a given type
*/
static copyToNewObject<T = Record<string, unknown>>(
source: any,
@ -360,7 +358,16 @@ export class Utils {
targetType?: new () => T
): T {
const target: any = targetType != null ? new targetType() : {};
return Utils.copyToObject(source, map, target);
}
/**
* Copies properties from a source object to a target object according to a mapping
* @param source The source to copy from
* @param map The mapping of source property names to target property names (target names are optional)
* @param target The target to copy to
*/
static copyToObject(source: any, map: { [sourcePropName: string]: string }, target: any): any {
Object.keys(map).forEach((sourcePropName) => {
const targetPropName = map[sourcePropName] ?? sourcePropName;
const value = source[sourcePropName];