Skip to content

Commit 483f3e6

Browse files
committed
feat: Add helpers to check types and values
1 parent 614a58b commit 483f3e6

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/helpers.ts

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
export const isEmpty = (obj: unknown): boolean => {
2+
if (obj == null) return true; // Handles null and undefined
3+
if (typeof obj === "string" || Array.isArray(obj)) return obj.length === 0;
4+
if (obj instanceof Map || obj instanceof Set) return obj.size === 0;
5+
if (typeof obj !== "object") return true;
6+
7+
return Object.keys(obj).length === 0;
8+
};
9+
10+
export const isObject = (value: unknown): value is Record<string, unknown> =>
11+
value instanceof Object;
12+
13+
export const isString = (value: unknown): value is string =>
14+
typeof value === "string";
15+
16+
export const isNull = (value: unknown): value is null => value === null;
17+
18+
export const isUndefined = (value: unknown): value is undefined =>
19+
value === undefined;
20+
21+
export const isMatch = <T extends Record<string, unknown>>(
22+
object: T,
23+
source: Partial<T>,
24+
): boolean => {
25+
for (const key in source) {
26+
if (!(key in object)) return false;
27+
28+
const sourceValue = source[key];
29+
const objectValue = object[key];
30+
31+
// For arrays, check if every element in `source` exists in `object`
32+
if (Array.isArray(sourceValue) && Array.isArray(objectValue)) {
33+
if (!sourceValue.every((v) => objectValue.includes(v)))
34+
return false;
35+
continue;
36+
}
37+
38+
// For objects, perform a deep comparison recursively
39+
if (
40+
typeof sourceValue === "object" &&
41+
sourceValue !== null &&
42+
typeof objectValue === "object" &&
43+
objectValue !== null
44+
) {
45+
if (
46+
!isMatch(
47+
objectValue as Record<string, unknown>,
48+
sourceValue as Record<string, unknown>,
49+
)
50+
) {
51+
return false;
52+
}
53+
continue;
54+
}
55+
56+
// Check for direct value equality
57+
if (objectValue !== sourceValue) return false;
58+
}
59+
60+
return true;
61+
};

0 commit comments

Comments
 (0)