File tree 2 files changed +54
-0
lines changed
2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change @@ -149,15 +149,35 @@ export function isMatch(
149
149
} ) ;
150
150
}
151
151
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
+ */
152
160
export function isEmpty ( input : Record < string , unknown > | null | undefined | unknown ) : input is null | undefined | Record < string , never > {
153
161
if ( input === null || input === undefined ) {
154
162
return true ;
155
163
}
156
164
157
165
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
+
158
174
return Object . getOwnPropertyNames ( input ) . length === 0 ;
159
175
}
160
176
177
+ if ( typeof input === "string" ) {
178
+ return input . trim ( ) . length === 0 || input === "{}" || input === "[]" ;
179
+ }
180
+
161
181
return false ;
162
182
}
163
183
Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ import { expect } from "expect";
3
3
4
4
import {
5
5
endsWith ,
6
+ isEmpty ,
6
7
isMatch ,
7
8
parseVersion ,
8
9
prune ,
@@ -609,6 +610,39 @@ describe("Utils", () => {
609
610
expect ( parseVersion ( "https://cdnjs.cloudflare.com/BLAH/BLAH.min.js" ) ) . toBeNull ( ) ;
610
611
} ) ;
611
612
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
+
612
646
describe ( "isMatch" , ( ) => {
613
647
test ( "input: blake patterns [\"pAssword\"]" , ( ) => {
614
648
expect ( isMatch ( "blake" , [ "pAssword" ] ) ) . toBe ( false ) ;
You can’t perform that action at this time.
0 commit comments