From 9cdde27e25b13714e24082a50673454693c954ef Mon Sep 17 00:00:00 2001 From: Bruno Boi Date: Mon, 17 May 2021 11:10:10 +0000 Subject: [IMP] web: add findWhere utils closes odoo/odoo#70936 Taskid: 2412172 Related: odoo/enterprise#18366 Signed-off-by: Aaron Bohy (aab) --- addons/web/static/src/js/core/utils.js | 19 +++++++++++++++++++ addons/web/static/tests/core/util_tests.js | 23 +++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/addons/web/static/src/js/core/utils.js b/addons/web/static/src/js/core/utils.js index a5a5f4eb465..50e54273ac9 100644 --- a/addons/web/static/src/js/core/utils.js +++ b/addons/web/static/src/js/core/utils.js @@ -267,6 +267,25 @@ var utils = { confine: function (val, min, max) { return Math.max(min, Math.min(max, val)); }, + /** + * Looks through the list and returns the first value that matches all + * of the key-value pairs listed in properties. + * If no match is found, or if list is empty, undefined will be returned. + * + * @param {Array} list + * @param {Object} props + * @returns {any|undefined} first element in list that matches all props + */ + findWhere: function (list, props) { + if (!Array.isArray(list) || !props) { + return; + } + return list.filter((item) => item !== undefined).find((item) => { + return Object.keys(props).every((key) => { + return item[key] === props[key]; + }) + }); + }, /** * @param {number} value * @param {integer} decimals diff --git a/addons/web/static/tests/core/util_tests.js b/addons/web/static/tests/core/util_tests.js index 6115833e4f2..88faab4463a 100644 --- a/addons/web/static/tests/core/util_tests.js +++ b/addons/web/static/tests/core/util_tests.js @@ -7,6 +7,29 @@ QUnit.module('core', {}, function () { QUnit.module('utils'); + QUnit.test('findWhere', function (assert) { + assert.expect(7); + + const { findWhere } = utils; + + const list = [ + undefined, + { a: 1, b: 2 }, + { a: 2, b: 2 }, + { a: 1, b: 3 }, + { a: 1, b: 4 }, + { a: 2, b: 4 }, + ]; + + assert.deepEqual(findWhere(list, { a: 1 }), { a: 1, b: 2 }); + assert.deepEqual(findWhere(list, { a: 2 }), { a: 2, b: 2 }); + assert.deepEqual(findWhere(list, { b: 4 }), { a: 1, b: 4 }); + assert.deepEqual(findWhere(list, { b: 4, a: 2 }), { a: 2, b: 4 }); + assert.ok(findWhere([], { a: 1 }) === undefined); + assert.ok(findWhere(list, { a: 1, b: 5 }) === undefined); + assert.ok(findWhere(list, { c: 1 }) === undefined); + }); + QUnit.test('groupBy', function (assert) { assert.expect(7); -- cgit v1.2.3