From 57a04c4aa3d8e1e8b74e2b5eea929aee1644c367 Mon Sep 17 00:00:00 2001 From: Mathieu Duckerts-Antoine Date: Thu, 6 Apr 2023 10:28:22 +0000 Subject: [PATCH] [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 --- addons/web/static/src/core/utils/arrays.js | 26 +++++++++++++++++++ .../static/tests/core/utils/arrays_tests.js | 18 +++++++++++++ 2 files changed, 44 insertions(+) diff --git a/addons/web/static/src/core/utils/arrays.js b/addons/web/static/src/core/utils/arrays.js index 0b449b21476..bd028a45c27 100644 --- a/addons/web/static/src/core/utils/arrays.js +++ b/addons/web/static/src/core/utils/arrays.js @@ -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)); +} diff --git a/addons/web/static/tests/core/utils/arrays_tests.js b/addons/web/static/tests/core/utils/arrays_tests.js index 6dd1a278b2e..9626a84af32 100644 --- a/addons/web/static/tests/core/utils/arrays_tests.js +++ b/addons/web/static/tests/core/utils/arrays_tests.js @@ -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] + ); + }); });