Can compare arrays

pull/2/head
Louis Chatriot 12 years ago
parent 07ff9e2183
commit cb840dec66
  1. 24
      lib/model.js
  2. 21
      test/model.test.js

@ -131,9 +131,9 @@ function deepCopy (obj) {
/**
* Utility function for comparing things
* Works for numbers, strings and booleans
* Utility functions for comparing things
* Assumes type checking was already done (a and b already have the same type)
* compareNSB works for numbers, strings and booleans
*/
function compareNSB (a, b) {
if (a < b) { return -1; }
@ -141,11 +141,25 @@ function compareNSB (a, b) {
return 0;
}
function compareArrays (a, b) {
var i, comp;
for (i = 0; i < Math.min(a.length, b.length); i += 1) {
comp = compareThings(a[i], b[i]);
if (comp !== 0) { return comp; }
}
// Common section was identical, longest one wins
return compareNSB(a.length, b.length);
}
/**
* Compare things
* Things are defined as any native types (string, number, boolean, null, date) and objects
* In the case of objects and arrays, we compare the serialized versions
* If two objects dont have the same type, the (arbitrary) type hierarchy is: null, number, strings, boolean, dates, objects, arrays
* If two objects dont have the same type, the (arbitrary) type hierarchy is: null, number, strings, boolean, dates, arrays, objects
* 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) {
@ -168,6 +182,10 @@ function compareThings (a, b) {
// Dates
if (util.isDate(a)) { return util.isDate(b) ? compareNSB(a.getTime(), b.getTime()) : -1; }
if (util.isDate(b)) { return util.isDate(a) ? compareNSB(a.getTime(), b.getTime()) : 1; }
// Arrays (first element is most significant and so on)
if (util.isArray(a)) { return util.isArray(b) ? compareArrays(a, b) : -1; }
if (util.isArray(b)) { return util.isArray(a) ? compareArrays(a, b) : 1; }
}

@ -415,6 +415,27 @@ describe('Model', function () {
});
});
it('Then arrays', function () {
var otherStuff = [{}, { hello: 'world' }]
, arrays = [[], ['yes'], ['hello', 5]]
;
model.compareThings([], []).should.equal(0);
model.compareThings(['hello'], []).should.equal(1);
model.compareThings([], ['hello']).should.equal(-1);
model.compareThings(['hello'], ['hello', 'world']).should.equal(-1);
model.compareThings(['hello', 'earth'], ['hello', 'world']).should.equal(-1);
model.compareThings(['hello', 'zzz'], ['hello', 'world']).should.equal(1);
model.compareThings(['hello', 'world'], ['hello', 'world']).should.equal(0);
otherStuff.forEach(function (stuff) {
arrays.forEach(function (array) {
model.compareThings(array, stuff).should.equal(-1);
model.compareThings(stuff, array).should.equal(1);
});
});
});
}); // ==== End of 'Comparing things' ==== //

Loading…
Cancel
Save