Skip to content

Commit

Permalink
Refactored deepMerge function to improve performance (#1211)
Browse files Browse the repository at this point in the history
  • Loading branch information
oekazuma authored Oct 25, 2024
1 parent 390d335 commit 3cf0b94
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 26 deletions.
5 changes: 5 additions & 0 deletions .changeset/late-coins-beam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte-meta-tags': patch
---

Refactored deepMerge function to improve performance
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ jobs:
run: pnpm build
- name: Install Playwright
run: pnpm dlx [email protected] install --with-deps
- name: Run Playwright
- name: Run Vitest and Playwright
run: pnpm test
5 changes: 0 additions & 5 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,6 @@ jobs:
- name: Checkout Repo
uses: actions/checkout@v4
- uses: pnpm/[email protected]
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.18.0'
cache: pnpm
- run: pnpm install --frozen-lockfile
- name: Create Release Pull Request or Publish to npm
id: changesets
Expand Down
39 changes: 19 additions & 20 deletions packages/svelte-meta-tags/src/lib/deepMerge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,25 @@
export const deepMerge = <X extends Record<string | symbol | number, any>>(target: X, source: X): X => {
if (!target || !source) return target ?? source ?? ({} as X);

return Object.entries({ ...target, ...source }).reduce((acc, [key, value]) => {
return {
...acc,
[key]: (() => {
if (target[key] instanceof Date || typeof target[key] === 'function') {
return target[key];
}
if (value instanceof Date || typeof value === 'function') {
return value;
}
if (isObject(target[key]) && isObject(value)) {
return deepMerge(target[key], value);
}
if (isArray(target[key]) && isArray(value)) {
return value;
}
return value !== undefined ? value : target[key];
})()
};
}, {} as X);
const result: Record<string | symbol | number, any> = { ...target };

for (const [key, value] of Object.entries(source)) {
const targetValue = target[key];

if (targetValue instanceof Date || typeof targetValue === 'function') {
result[key] = targetValue;
} else if (value instanceof Date || typeof value === 'function') {
result[key] = value;
} else if (isObject(targetValue) && isObject(value)) {
result[key] = deepMerge(targetValue, value);
} else if (isArray(targetValue) && isArray(value)) {
result[key] = value;
} else {
result[key] = value !== undefined ? value : targetValue;
}
}

return result as X;
};

const isObject = (obj: any): obj is Record<string | symbol | number, any> =>
Expand Down

0 comments on commit 3cf0b94

Please sign in to comment.