[IMP] web: Ensure array utility function

This commit introduces the `ensureArray` function, ensuring that the
given argument is an array by wrapping it in one if it is not.

Part of task 3121497

Part-of: odoo/odoo#112171
This commit is contained in:
Julien Mougenot
2023-05-05 13:52:21 +02:00
parent 437edce313
commit f853ca8eec
2 changed files with 21 additions and 0 deletions
@@ -53,6 +53,14 @@ function _getExtractorFrom(criterion) {
}
}
/**
* @template T
* @param {T | T[]} value
*/
export function ensureArray(value) {
return value && typeof value === "object" && value[Symbol.iterator] ? [...value] : [value];
}
/**
* Returns the array of elements contained in both arrays.
*
@@ -2,6 +2,7 @@
import {
cartesian,
ensureArray,
groupBy,
intersection,
shallowEqual,
@@ -238,6 +239,18 @@ QUnit.module("utils", () => {
assert.deepEqual(cartesian([1], [2], [3], [4]), [[1, 2, 3, 4]]);
});
QUnit.test("ensure array", async (assert) => {
const arrayRef = [];
assert.notEqual(ensureArray(arrayRef), arrayRef, "Should be a different array");
assert.deepEqual(ensureArray([]), []);
assert.deepEqual(ensureArray(), [undefined]);
assert.deepEqual(ensureArray(null), [null]);
assert.deepEqual(ensureArray({ a: 1 }), [{ a: 1 }]);
assert.deepEqual(ensureArray("foo"), ["foo"]);
assert.deepEqual(ensureArray([1, 2, "3"]), [1, 2, "3"]);
assert.deepEqual(ensureArray(new Set([1, 2, 3])), [1, 2, 3]);
});
QUnit.test("unique array", function (assert) {
assert.deepEqual(unique([1, 2, 3, 2, 4, 3, 1, 4]), [1, 2, 3, 4]);
assert.deepEqual(unique("a d c a b c d b".split(" ")), "a d c b".split(" "));