Skip to content

Commit aaf2b06

Browse files
committed
Improved empty checks and added basic tests
1 parent 989830e commit aaf2b06

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

packages/core/src/Utils.ts

+20
Original file line numberDiff line numberDiff line change
@@ -149,15 +149,35 @@ export function isMatch(
149149
});
150150
}
151151

152+
/**
153+
* Very simple implementation to check primitive types for emptiness.
154+
* - If the input is null or undefined, it will return true.
155+
* - If the input is an array, it will return true if the array is empty.
156+
* - If the input is an object, it will return true if the object has no properties.
157+
* - If the input is a string, it will return true if the string is empty or "{}" or "[]".
158+
* @param input The input to check.
159+
*/
152160
export function isEmpty(input: Record<string, unknown> | null | undefined | unknown): input is null | undefined | Record<string, never> {
153161
if (input === null || input === undefined) {
154162
return true;
155163
}
156164

157165
if (typeof input === "object") {
166+
if (Array.isArray(input)) {
167+
return input.length === 0;
168+
}
169+
170+
if (input instanceof Date) {
171+
return false;
172+
}
173+
158174
return Object.getOwnPropertyNames(input).length === 0;
159175
}
160176

177+
if (typeof input === "string") {
178+
return input.trim().length === 0 || input === "{}" || input === "[]";
179+
}
180+
161181
return false;
162182
}
163183

packages/core/test/Utils.test.ts

+34
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { expect } from "expect";
33

44
import {
55
endsWith,
6+
isEmpty,
67
isMatch,
78
parseVersion,
89
prune,
@@ -609,6 +610,39 @@ describe("Utils", () => {
609610
expect(parseVersion("https://cdnjs.cloudflare.com/BLAH/BLAH.min.js")).toBeNull();
610611
});
611612

613+
describe("isEmpty", () => {
614+
const emptyValues = {
615+
"undefined": undefined,
616+
"null": null,
617+
"empty string": "",
618+
"whitespace string": " ",
619+
"{} string": "{}",
620+
"[] string": "[]",
621+
"empty object": {},
622+
"empty array": []
623+
};
624+
625+
Object.entries(emptyValues).forEach(([key, value]) => {
626+
test(`for ${key}`, () => {
627+
expect(isEmpty(value)).toBe(true);
628+
});
629+
});
630+
631+
const values = {
632+
"Date": new Date(),
633+
"number": 1,
634+
"string": "string",
635+
"object": { a: 1 },
636+
"array": [1]
637+
};
638+
639+
Object.entries(values).forEach(([key, value]) => {
640+
test(`for ${key}`, () => {
641+
expect(isEmpty(value)).toBe(false);
642+
});
643+
});
644+
});
645+
612646
describe("isMatch", () => {
613647
test("input: blake patterns [\"pAssword\"]", () => {
614648
expect(isMatch("blake", ["pAssword"])).toBe(false);

0 commit comments

Comments
 (0)