Skip to content

Commit

Permalink
perf: reduce footprint
Browse files Browse the repository at this point in the history
  • Loading branch information
noomorph committed Oct 27, 2023
1 parent 073e47a commit 5213ff9
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/utils/get.ts
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;
}
23 changes: 23 additions & 0 deletions src/utils/merge.ts
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;
}
15 changes: 15 additions & 0 deletions src/utils/set.ts
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];
}
}
}

0 comments on commit 5213ff9

Please sign in to comment.