From 0f912ed57fa81a0b444ec73cf31e92a3bac3912e Mon Sep 17 00:00:00 2001 From: Karolina Rusin Date: Thu, 21 May 2015 22:37:49 +0200 Subject: [PATCH] Add sort function that takes prefers ADDition over REMOVAL Fixes #5 --- json-diff.js | 9 +++++++-- test/spec/json-diff-spec.js | 12 ++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/json-diff.js b/json-diff.js index eef3557..aaf3bfc 100644 --- a/json-diff.js +++ b/json-diff.js @@ -72,7 +72,7 @@ function getDiffRepresentation(left, right) { result.push(new Diff(key, _getInDepthArrayDiff(value, op), op, ARRAY)); } } - result.sort(function(a,b) {return (a.key > b.key) ? 1 : ((b.key > a.key) ? -1 : 0);} ); + result.sort(_sortByKeyAndOp); return result; } @@ -145,10 +145,15 @@ function getDiffRepresentation(left, right) { } } - result.sort(function(a,b) {return (a.key > b.key) ? 1 : ((b.key > a.key) ? -1 : 0);} ); + result.sort(_sortByKeyAndOp); return result; } + function _sortByKeyAndOp(a, b){ + if (a.key === b.key) return (a.op === ADD) ? -1 : (a.op === REMOVE) ? 1 : 0; + return a.key > b.key ? 1 : (b.key > a.key) ? -1 : 0; + } + var leftJson = JSON.parse(left); var rightJson = JSON.parse(right); diff --git a/test/spec/json-diff-spec.js b/test/spec/json-diff-spec.js index 3e4f3be..1f23f16 100644 --- a/test/spec/json-diff-spec.js +++ b/test/spec/json-diff-spec.js @@ -170,4 +170,16 @@ describe("Get Json diff representation", function() { expect(result.diff[0].value[2].value).toEqual(12); expect(result.diff[0].value[2].key).toEqual("e"); }); + + it("Diff should be sorted by key and operation", function() { + var result = getDiffRepresentation("{\"a\":1}", "{\"a\":\"1\"}"); + + expect(result.type).toEqual(OBJECT); + expect(result.diff[0].key).toEqual("a"); + expect(result.diff[0].op).toEqual(ADD); + expect(result.diff[0].valueType).toEqual(SCALAR); + expect(result.diff[1].key).toEqual("a"); + expect(result.diff[1].op).toEqual(REMOVE); + expect(result.diff[1].valueType).toEqual(SCALAR); + }) });