summaryrefslogtreecommitdiff
path: root/addons/web/static/src
diff options
context:
space:
mode:
authorJulien Mougenot <jum@odoo.com>2020-04-29 09:52:18 +0000
committerMathieu Duckerts-Antoine <dam@odoo.com>2020-05-05 19:23:20 +0000
commit26491fcb4ce1e21584be0454a4178f8249ec75a9 (patch)
tree712c16df27cbb7d13f88fecdd84fe7f874dad1c1 /addons/web/static/src
parentd64c8fa304279f52ae426bfa8f451617cba9aa06 (diff)
[IMP] web: add sortBy to core.utils
Add a "sortBy" helper to core utils. This function takes an array and an optional criterion as arguments and returns a new array sorted according to the given criterion.
Diffstat (limited to 'addons/web/static/src')
-rw-r--r--addons/web/static/src/js/core/utils.js36
1 files changed, 33 insertions, 3 deletions
diff --git a/addons/web/static/src/js/core/utils.js b/addons/web/static/src/js/core/utils.js
index 1e3c6074857..560f3a94466 100644
--- a/addons/web/static/src/js/core/utils.js
+++ b/addons/web/static/src/js/core/utils.js
@@ -447,7 +447,7 @@ var utils = {
},
/**
* Checks if a class is an extension of owl.Component.
- *
+ *
* @param {any} value A class reference
*/
isComponent: function (value) {
@@ -527,12 +527,12 @@ var utils = {
/**
* Patch a class and return a function that remove the patch
* when called.
- *
+ *
* This function is the last resort solution for monkey-patching an
* ES6 Class, for people that do not control the code defining the Class
* to patch (e.g. partners), and when that Class isn't patchable already
* (i.e. when it doesn't have a 'patch' function, defined by the 'web.patchMixin').
- *
+ *
* @param {Class} C Class to patch
* @param {string} patchName
* @param {Object} patch
@@ -650,6 +650,36 @@ var utils = {
].join(';');
},
/**
+ * Return a shallow copy of a given array sorted by a given criterion or a default one.
+ * The given criterion can either be:
+ * - a string: a property name on the array elements returning the sortable primitive
+ * - a function: a handler that will return the sortable primitive from a given element.
+ *
+ * @param {any[]} array
+ * @param {(string|function)} [criterion]
+ */
+ sortBy: function (array, criterion) {
+ let getter;
+ if (criterion) {
+ switch (typeof criterion) {
+ case 'string': getter = element => element[criterion]; break;
+ case 'function': getter = criterion; break;
+ default: throw new Error(`Expected criterion of type 'string' or 'function' and got '${typeof criterion}'`);
+ }
+ } else {
+ getter = element => element;
+ }
+ return array.slice().sort((elA, elB) => {
+ const a = getter(elA);
+ const b = getter(elB);
+ if (isNaN(a) && isNaN(b)) {
+ return a > b ? 1 : a < b ? -1 : 0;
+ } else {
+ return a - b;
+ }
+ });
+ },
+ /**
* Returns a string formatted using given values.
* If the value is an object, its keys will replace `%(key)s` expressions.
* If the values are a set of strings, they will replace `%s` expressions.