File tree Expand file tree Collapse file tree 2 files changed +43
-2
lines changed Expand file tree Collapse file tree 2 files changed +43
-2
lines changed Original file line number Diff line number Diff line change @@ -554,9 +554,22 @@ const jqToNode = (el) => {
554
554
return el ;
555
555
} ;
556
556
557
- const ensureArray = ( it ) => {
557
+ /**
558
+ * Always return an iterable object.
559
+ *
560
+ * @param {any } it: The object which needs to be wrapped in an array or returned as is if it is iterable.
561
+ * @param {boolean } force_array: If the object is iterable but not an Array, convert it to an array (e.g. For jQuery items or NodeList objects).
562
+ *
563
+ * @returns {Array }: Returns the object wrapped in an Array, expanded to an Array or as-is if it is already iterable.
564
+ */
565
+ const ensureArray = ( it , force_array ) => {
558
566
// Ensure to return always an array
559
- return Array . isArray ( it ) || it . jquery ? it : [ it ] ;
567
+ const array_like = ! ! (
568
+ NodeList . prototype . isPrototypeOf ( it ) || // eslint-disable-line no-prototype-builtins
569
+ Array . isArray ( it ) ||
570
+ it . jquery
571
+ ) ;
572
+ return array_like ? ( force_array ? [ ...it ] : it ) : [ it ] ;
560
573
} ;
561
574
562
575
const localized_isodate = ( date ) => {
Original file line number Diff line number Diff line change @@ -642,6 +642,34 @@ describe("core.utils tests", () => {
642
642
643
643
done ( ) ;
644
644
} ) ;
645
+
646
+ it ( "returns a array-like NodeList object as is" , ( ) => {
647
+ const el = document . createElement ( "div" ) ;
648
+ el . innerHTML = `
649
+ <div></div>
650
+ <div></div>
651
+ <div></div>
652
+ ` ;
653
+ const node_list = el . querySelectorAll ( "div" ) ;
654
+ const result = utils . ensureArray ( node_list ) ;
655
+ expect ( result . length ) . toBe ( 3 ) ;
656
+ expect ( NodeList . prototype . isPrototypeOf ( result ) ) . toBe ( true ) ; // eslint-disable-line no-prototype-builtins
657
+ expect ( Array . isArray ( result ) ) . toBe ( false ) ;
658
+ } ) ;
659
+
660
+ it ( "returns a array from a NodeList is force_array is set" , ( ) => {
661
+ const el = document . createElement ( "div" ) ;
662
+ el . innerHTML = `
663
+ <div></div>
664
+ <div></div>
665
+ <div></div>
666
+ ` ;
667
+ const node_list = el . querySelectorAll ( "div" ) ;
668
+ const result = utils . ensureArray ( node_list , true ) ;
669
+ expect ( result . length ) . toBe ( 3 ) ;
670
+ expect ( NodeList . prototype . isPrototypeOf ( result ) ) . toBe ( false ) ; // eslint-disable-line no-prototype-builtins
671
+ expect ( Array . isArray ( result ) ) . toBe ( true ) ;
672
+ } ) ;
645
673
} ) ;
646
674
647
675
describe ( "localized_isodate tests" , ( ) => {
You can’t perform that action at this time.
0 commit comments