-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(hub-common): adds a setProp utility
affects: @esri/hub-common
- Loading branch information
1 parent
145edb2
commit c6290e6
Showing
3 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } }); | ||
}); | ||
}); |