Skip to content

Commit 23336b9

Browse files
committed
feat(core utils): Support NodeList in ensureArray and add option enforce_array if an array-like object should converted to a real array.
1 parent 03437e9 commit 23336b9

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

src/core/utils.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -554,9 +554,22 @@ const jqToNode = (el) => {
554554
return el;
555555
};
556556

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) => {
558566
// 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];
560573
};
561574

562575
const localized_isodate = (date) => {

src/core/utils.test.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,34 @@ describe("core.utils tests", () => {
642642

643643
done();
644644
});
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+
});
645673
});
646674

647675
describe("localized_isodate tests", () => {

0 commit comments

Comments
 (0)