[REF] web,*: Centralize shallowEqual

Before this commit, 2 implementations of a "shallowEqual" function
coexisted, one in 'web/core/utils/objects.js' and another in
'web/core/utils/arrays.js'.

This commit only keeps the one in objects.js and makes the other simply
import and export it as well (easier to maintain while also easier to
find for those who want to work with arrays), while also taking an
optional comparison function argument in case the comparison needs to be
more specific (e.g. compare DateTime objects).

Part-of: odoo/odoo#125039
This commit is contained in:
Julien Mougenot
2023-07-03 12:21:05 +02:00
parent 592794b397
commit e74672d71d
3 changed files with 21 additions and 23 deletions
+3 -18
View File
@@ -1,5 +1,7 @@
/** @odoo-module **/
import { shallowEqual as _shallowEqual } from "./objects";
/**
* Same values returned as those returned by cartesian function for case n = 0
* and n > 1. For n = 1, brackets are put around the unique parameter elements.
@@ -165,24 +167,7 @@ export function cartesian() {
}
}
/**
* Shallow compares two arrays.
* @template T
* @param {T[]} arrayA
* @param {T[]} arrayB
* @returns {boolean} true iff arrayA and arrayB are shallow equal
*/
export function shallowEqual(arrayA, arrayB) {
if (arrayA.length !== arrayB.length) {
return false;
}
for (let i = 0; i < arrayA.length; i++) {
if (arrayA[i] !== arrayB[i]) {
return false;
}
}
return true;
}
export const shallowEqual = _shallowEqual;
/**
* Returns all initial sections of a given array, e.g. for [1, 2] the array
+9 -5
View File
@@ -3,15 +3,19 @@
/**
* Shallow compares two objects.
*
* @param {Record<string, any>} obj1
* @param {Record<string, any>} obj2
* @returns {boolean}
* @template {unknown} T
* @param {T} obj1
* @param {T} obj2
* @param {(a: T[keyof T], b: T[keyof T]) => boolean} [comparisonFn]
*/
export function shallowEqual(obj1, obj2) {
export function shallowEqual(obj1, obj2, comparisonFn = (a, b) => a === b) {
if (!obj1 || !obj2 || typeof obj1 !== "object" || typeof obj2 !== "object") {
return obj1 === obj2;
}
const obj1Keys = Object.keys(obj1);
return (
obj1Keys.length === Object.keys(obj2).length &&
obj1Keys.every((key) => obj1[key] === obj2[key])
obj1Keys.every((key) => comparisonFn(obj1[key], obj2[key]))
);
}
@@ -57,4 +57,13 @@ QUnit.module("utils", () => {
assert.ok(shallowEqual({ a: fn }, { a: fn }));
assert.notOk(shallowEqual({ a: () => {} }, { a: () => {} }));
});
QUnit.test("shallowEqual: custom comparison function", function (assert) {
assert.notOk(shallowEqual({ a: 1, date: new Date() }, { a: 1, date: new Date() }));
assert.ok(
shallowEqual({ a: 1, date: new Date() }, { a: 1, date: new Date() }, (a, b) =>
a instanceof Date ? Number(a) === Number(b) : a === b
)
);
});
});