Skip to content

Commit

Permalink
feat(hub-common): adds a setProp utility
Browse files Browse the repository at this point in the history
affects: @esri/hub-common
  • Loading branch information
drewdaemon committed Mar 31, 2021
1 parent 145edb2 commit c6290e6
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/common/src/objects/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export * from "./get-with-default";
export * from "./remove-empty-props";
export * from "./deep-string-replace";
export * from "./merge-objects";
export * from "./set-prop";
22 changes: 22 additions & 0 deletions packages/common/src/objects/set-prop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Sets a deep object property, constructing the property path as necessary
*
* @param path - the path to the property we want to set
* @param val - the value we want to set it to
* @param obj - the target object
*/
export function setProp(path: string | string[], val: any, obj: any): boolean {
const props = Array.isArray(path) ? path : path.split(".");
if (props.length > 1) {
// does the object have this prop? if not, create it as an object
if (!obj.hasOwnProperty(props[0])) {
obj[props[0]] = {};
}
return setProp(props.slice(1), val, obj[props[0]]);
// recurse back into this, but with one less entry in the props
} else {
// this is the last one, the one we want to replace
obj[props[0]] = val;
return true;
}
}
21 changes: 21 additions & 0 deletions packages/common/test/objects/set-prop.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { setProp } from "../../src";

describe("setProp", () => {
it("works with a string path", async () => {
const obj = {};
setProp("foo.bar", true, obj);
expect(obj).toEqual({ foo: { bar: true } });
});

it("works with an array path", async () => {
const obj = {};
setProp(["foo", "bar"], true, obj);
expect(obj).toEqual({ foo: { bar: true } });
});

it("uses an existing path when available", async () => {
const obj = { foo: { bar: false } };
setProp(["foo", "bar"], true, obj);
expect(obj).toEqual({ foo: { bar: true } });
});
});

0 comments on commit c6290e6

Please sign in to comment.