Skip to content

Commit

Permalink
Add isEmptyObject() object util
Browse files Browse the repository at this point in the history
  • Loading branch information
techniq committed Mar 21, 2024
1 parent fc50ca2 commit e2b97b6
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/small-scissors-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"svelte-ux": patch
---

Add `isEmptyObject()` util
8 changes: 6 additions & 2 deletions packages/svelte-ux/src/lib/utils/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ export function isLiteralObject(obj: any): obj is object {
return obj && typeof obj === 'object' && obj.constructor === Object;
}

export function isEmptyObject(obj: any) {
return isLiteralObject(obj) && Object.keys(obj).length === 0;
}

export function camelCaseKeys(obj: any) {
return Object.keys(obj).reduce((acc, key) => ((acc[camelCase(key)] = obj[key]), acc), {} as any);
}
Expand Down Expand Up @@ -123,15 +127,15 @@ export function expireObject<TObject extends object>(
expireObject(value, propExpiry);

// Remove property if empty object (all properties removed)
if (isLiteralObject(value) && Object.keys(value).length === 0) {
if (isEmptyObject(value)) {
delete object[prop as keyof TObject];
}
}
}
}
}

return isLiteralObject(object) && Object.keys(object).length === 0 ? null : object;
return isEmptyObject(object) ? null : object;
}

/**
Expand Down
3 changes: 2 additions & 1 deletion packages/svelte-ux/src/lib/utils/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { parse, reviver, stringify } from './json.js';
import { isEmptyObject } from './object.js';

// See: https://github.com/pbeshai/serialize-query-params/blob/master/src/serialize.ts

Expand Down Expand Up @@ -457,7 +458,7 @@ export function encodeObject(
entrySeparator = '_'
): string | null | undefined {
if (obj == null) return obj; // null or undefined
if (!Object.keys(obj).length) return ''; // {} case
if (isEmptyObject(obj)) return ''; // {} case

return Object.keys(obj)
.map((key) => {
Expand Down

0 comments on commit e2b97b6

Please sign in to comment.