[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:
@@ -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(" "));
|
||||
|
||||
Reference in New Issue
Block a user