Can compare all things

pull/2/head
Louis Chatriot 12 years ago
parent cb840dec66
commit 8aa0753c02
  1. 14
      lib/model.js
  2. 10
      test/model.test.js

@ -163,6 +163,8 @@ function compareArrays (a, b) {
* Return -1 if a < b, 1 if a > b and 0 if a = b (note that equality here is NOT the same as defined in areThingsEqual!) * Return -1 if a < b, 1 if a > b and 0 if a = b (note that equality here is NOT the same as defined in areThingsEqual!)
*/ */
function compareThings (a, b) { function compareThings (a, b) {
var aKeys, bKeys, comp, i;
// null is less than everything except null // null is less than everything except null
if (a === null) { return b === null ? 0 : -1; } if (a === null) { return b === null ? 0 : -1; }
if (b === null) { return a === null ? 0 : 1; } if (b === null) { return a === null ? 0 : 1; }
@ -186,6 +188,18 @@ function compareThings (a, b) {
// Arrays (first element is most significant and so on) // Arrays (first element is most significant and so on)
if (util.isArray(a)) { return util.isArray(b) ? compareArrays(a, b) : -1; } if (util.isArray(a)) { return util.isArray(b) ? compareArrays(a, b) : -1; }
if (util.isArray(b)) { return util.isArray(a) ? compareArrays(a, b) : 1; } if (util.isArray(b)) { return util.isArray(a) ? compareArrays(a, b) : 1; }
// Objects
aKeys = Object.keys(a).sort();
bKeys = Object.keys(b).sort();
for (i = 0; i < Math.min(aKeys.length, bKeys.length); i += 1) {
comp = compareThings(a[aKeys[i]], b[bKeys[i]]);
if (comp !== 0) { return comp; }
}
return compareNSB(aKeys.length, bKeys.length);
} }

@ -329,7 +329,7 @@ describe('Model', function () {
}); // ==== End of 'Modifying documents' ==== // }); // ==== End of 'Modifying documents' ==== //
describe.only('Comparing things', function () { describe('Comparing things', function () {
it('null is less than everything except null', function () { it('null is less than everything except null', function () {
var otherStuff = ["string", "", -1, 0, 5.3, 12, true, false, new Date(12345), {}, { hello: 'world' }, [], ['quite', 5]]; var otherStuff = ["string", "", -1, 0, 5.3, 12, true, false, new Date(12345), {}, { hello: 'world' }, [], ['quite', 5]];
@ -436,6 +436,14 @@ describe('Model', function () {
}); });
}); });
it('And finally objects', function () {
model.compareThings({}, {}).should.equal(0);
model.compareThings({ a: 42 }, { a: 312}).should.equal(-1);
model.compareThings({ a: '42' }, { a: '312'}).should.equal(1);
model.compareThings({ a: 42, b: 312 }, { b: 312, a: 42 }).should.equal(0);
model.compareThings({ a: 42, b: 312, c: 54 }, { b: 313, a: 42 }).should.equal(-1);
});
}); // ==== End of 'Comparing things' ==== // }); // ==== End of 'Comparing things' ==== //

Loading…
Cancel
Save