diff options
| author | Bruno Boi <boi@odoo.com> | 2021-05-17 11:10:10 +0000 |
|---|---|---|
| committer | Bruno Boi <boi@odoo.com> | 2021-05-28 13:29:21 +0000 |
| commit | 9cdde27e25b13714e24082a50673454693c954ef (patch) | |
| tree | 28c4066d02c1240447e0df06b9cca2aa71042603 /addons/web | |
| parent | 2ac6492cc29b7300cf1ab1635222d3b96ea5507d (diff) | |
[IMP] web: add findWhere utils
closes odoo/odoo#70936
Taskid: 2412172
Related: odoo/enterprise#18366
Signed-off-by: Aaron Bohy (aab) <aab@odoo.com>
Diffstat (limited to 'addons/web')
| -rw-r--r-- | addons/web/static/src/js/core/utils.js | 19 | ||||
| -rw-r--r-- | addons/web/static/tests/core/util_tests.js | 23 |
2 files changed, 42 insertions, 0 deletions
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 @@ -268,6 +268,25 @@ var utils = { 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 * @returns {boolean} 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); |
