Skip to content

Commit

Permalink
feat(essentials): add whereDefined and filterObject utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
thijsdaniels committed Aug 14, 2024
1 parent b099c0d commit e2ba61f
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/lemon-pumas-marry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@codedazur/essentials": minor
---

The filterObject and whereDefined object utilities were added.
13 changes: 13 additions & 0 deletions packages/essentials/utilities/object/filterObject.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { describe, it, expect } from "vitest";
import { filterObject } from "./filterObject";

describe("filterObject", () => {
it("filters an object", () => {
expect(
filterObject(
{ a: 1, b: 2, c: 3 },
([key, value]) => key === "a" || value === 3,
),
).toEqual({ a: 1, c: 3 });
});
});
12 changes: 12 additions & 0 deletions packages/essentials/utilities/object/filterObject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Filters an object by its entries.
*/
export function filterObject<
U extends Record<string, unknown>,
T extends Record<string, unknown> = Record<string, unknown>,
K extends keyof T = keyof T,
>(object: T, callback: (entry: [K, T[K]]) => boolean): U {
return Object.fromEntries(
(Object.entries(object) as [K, T[K]][]).filter(callback),
) as U;
}
20 changes: 20 additions & 0 deletions packages/essentials/utilities/object/whereDefined.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, it, expect } from "vitest";
import { whereDefined } from "./whereDefined";

describe("whereDefined", () => {
it("removes undefined properties", () => {
expect(
whereDefined({
a: 0,
b: "",
c: false,
d: null,
e: undefined,
}),
).toEqual({
a: 0,
b: "",
c: false,
});
});
});
17 changes: 17 additions & 0 deletions packages/essentials/utilities/object/whereDefined.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { filterObject } from "./filterObject";

/**
* Removes properties from an object that are `null` or `undefined`.
*/
export type WhereDefined<T> = {
[P in keyof T]-?: WhereDefined<NonNullable<T[P]>>;
};

/**
* Removes properties from an object that are `null` or `undefined`.
*/
export function whereDefined<T extends Record<string, unknown>>(
object: T,
): WhereDefined<T> {
return filterObject(object, ([, value]) => value !== undefined);
}

0 comments on commit e2ba61f

Please sign in to comment.