diff --git a/grails-app/assets/javascripts/forms.js b/grails-app/assets/javascripts/forms.js index de9a20c..da771c3 100644 --- a/grails-app/assets/javascripts/forms.js +++ b/grails-app/assets/javascripts/forms.js @@ -296,7 +296,27 @@ 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 (_.isArray(obj)) { + obj.sort(); + } else if (typeof obj === 'object' && obj !== null) { + for (var key in obj) { + sortArraysInObject(obj[key]); // Recursively call to sort arrays in nested objects + } + } + + return obj; + } + + 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 472e8eb..ab96973 100644 --- a/src/test/js/spec/ExpressionSpec.js +++ b/src/test/js/spec/ExpressionSpec.js @@ -124,4 +124,43 @@ describe("Expression Spec", 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(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 = { + a: {c: [1, 2]}, + b: {c: [3, 2, 1]} + }; + var result = ecodata.forms.expressionEvaluator.evaluateBoolean("deepEquals(a, b)", data); + expect(result).toEqual(false); + }) + }); \ No newline at end of file