From 386e0f23f55fd0927f89edccaf0fc8d999c2ccfe Mon Sep 17 00:00:00 2001 From: temi Date: Thu, 18 Apr 2024 11:18:29 +1000 Subject: [PATCH] #243 - added config option to specify if sorting is required - refactored code --- grails-app/assets/javascripts/forms.js | 13 +++++++++---- src/test/js/spec/ExpressionSpec.js | 20 ++++++++++++++++++-- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/grails-app/assets/javascripts/forms.js b/grails-app/assets/javascripts/forms.js index f498e96..da771c3 100644 --- a/grails-app/assets/javascripts/forms.js +++ b/grails-app/assets/javascripts/forms.js @@ -296,10 +296,12 @@ function orEmptyArray(v) { return _.findWhere(list, obj); }; - parser.functions.deepEquals = function(value1, value2) { + parser.functions.deepEquals = function(value1, value2, isSortArray) { + // set isSortArray to true if content of array is important and not the order i.e. [1,2,3] == [3,2,1] + isSortArray = isSortArray || false; // Sort arrays in nested objects to ensure that lodash compares arrays correctly function sortArraysInObject(obj) { - if (Array.isArray(obj)) { + if (_.isArray(obj)) { obj.sort(); } else if (typeof obj === 'object' && obj !== null) { for (var key in obj) { @@ -310,8 +312,11 @@ function orEmptyArray(v) { return obj; } - sortArraysInObject(value1); - sortArraysInObject(value2); + if (isSortArray) { + sortArraysInObject(value1); + sortArraysInObject(value2); + } + return _.isEqual(value1, value2); }; diff --git a/src/test/js/spec/ExpressionSpec.js b/src/test/js/spec/ExpressionSpec.js index 1feb491..ab96973 100644 --- a/src/test/js/spec/ExpressionSpec.js +++ b/src/test/js/spec/ExpressionSpec.js @@ -124,19 +124,35 @@ describe("Expression Spec", function () { }); - it("Should be able to compare two unsorted arrays", function() { + it("Should be able to compare two arrays", function() { var data = { a: [1, 2, 3], b: [3, 2, 1] }; + // unsorted arrays var result = ecodata.forms.expressionEvaluator.evaluateBoolean("deepEquals(a, b)", data); - expect(result).toEqual(true); + expect(result).toEqual(false); data = { a: {c: [1, 2, 3]}, b: {c: [3, 2, 1]} }; var result = ecodata.forms.expressionEvaluator.evaluateBoolean("deepEquals(a, b)", data); + expect(result).toEqual(false); + + // enable array sorting + var data = { + a: [1, 2, 3], + b: [3, 2, 1] + }; + var result = ecodata.forms.expressionEvaluator.evaluateBoolean("deepEquals(a, b, true)", data); + expect(result).toEqual(true); + + data = { + a: {c: [1, 2, 3]}, + b: {c: [3, 2, 1]} + }; + var result = ecodata.forms.expressionEvaluator.evaluateBoolean("deepEquals(a, b, true)", data); expect(result).toEqual(true); data = {