-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
52 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
export function get(obj: unknown, pathArray: string[], defaultValue: unknown): unknown { | ||
if (!obj) { | ||
return defaultValue; | ||
} | ||
|
||
let result = obj as any; | ||
for (const key of pathArray) { | ||
if (result[key] === undefined) { | ||
return defaultValue; | ||
} | ||
result = result[key]; | ||
} | ||
return result; | ||
} |
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,23 @@ | ||
function canAccessProperties(obj: unknown): obj is Record<string, unknown> { | ||
return !!obj && (typeof obj === 'object' || typeof obj === 'function'); | ||
} | ||
|
||
export function deepMerge(target: unknown, source: unknown): unknown { | ||
if (!canAccessProperties(target) || !canAccessProperties(source)) { | ||
return source; | ||
} | ||
|
||
const keys = Object.keys(source); | ||
for (const key of keys) { | ||
if (canAccessProperties(source[key])) { | ||
if (!target[key]) { | ||
target[key] = {}; | ||
} | ||
deepMerge(target[key], source[key]); | ||
} else { | ||
target[key] = source[key]; | ||
} | ||
} | ||
|
||
return target; | ||
} |
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,15 @@ | ||
export function set(obj: unknown, pathArray: string[], value: unknown): void { | ||
let temp: any = obj ?? {}; | ||
for (let i = 0; i < pathArray.length; i++) { | ||
const key = pathArray[i]; | ||
if (i === pathArray.length - 1) { | ||
// If it's the last key in the path | ||
temp[key] = value; | ||
} else { | ||
if (temp[key] === undefined) { | ||
temp[key] = {}; | ||
} | ||
temp = temp[key]; | ||
} | ||
} | ||
} |