[IMP] web: utils: zip and zipWith functions
We introduce in utils/arrays.js, the two classical functions zip and zipWith. Part-of: odoo/odoo#117882
This commit is contained in:
@@ -203,3 +203,29 @@ export function sections(array) {
|
||||
export function unique(array) {
|
||||
return Array.from(new Set(array));
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T1, T2, T
|
||||
* @param {T1[]} array1
|
||||
* @param {T2[]} array2
|
||||
* @returns {T[]}
|
||||
*/
|
||||
export function zip(array1, array2) {
|
||||
const result = [];
|
||||
const minLength = Math.min(array1.length, array2.length);
|
||||
for (let i = 0; i < minLength; i++) {
|
||||
result.push([array1[i], array2[i]]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T1, T2, T
|
||||
* @param {T1[]} array1
|
||||
* @param {T2[]} array2
|
||||
* @param {(e1: T1, e2: T2) => T} func
|
||||
* @returns {T[]}
|
||||
*/
|
||||
export function zipWith(array1, array2, func) {
|
||||
return zip(array1, array2).map(([e1, e2]) => func(e1, e2));
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
shallowEqual,
|
||||
sortBy,
|
||||
unique,
|
||||
zip,
|
||||
zipWith,
|
||||
} from "@web/core/utils/arrays";
|
||||
|
||||
QUnit.module("utils", () => {
|
||||
@@ -266,4 +268,20 @@ QUnit.module("utils", () => {
|
||||
assert.ok(shallowEqual([fn], [fn]));
|
||||
assert.notOk(shallowEqual([() => {}], [() => {}]));
|
||||
});
|
||||
|
||||
QUnit.test("zip", function (assert) {
|
||||
assert.deepEqual(zip([1, 2], []), []);
|
||||
assert.deepEqual(zip([1, 2], ["a"]), [[1, "a"]]);
|
||||
assert.deepEqual(zip([1, 2], ["a", "b"]), [
|
||||
[1, "a"],
|
||||
[2, "b"],
|
||||
]);
|
||||
});
|
||||
|
||||
QUnit.test("zipWith", function (assert) {
|
||||
assert.deepEqual(
|
||||
zipWith([{ a: 1 }, { b: 2 }], ["a", "b"], (o, k) => o[k]),
|
||||
[1, 2]
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user