From fdc01721e030a3a35d87e2419632a56adb63b583 Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Tue, 28 May 2013 15:56:28 +0200 Subject: [PATCH] Can compare booleans --- lib/model.js | 15 ++++++++++----- test/model.test.js | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/lib/model.js b/lib/model.js index c710898..62990b5 100644 --- a/lib/model.js +++ b/lib/model.js @@ -132,9 +132,10 @@ function deepCopy (obj) { /** * Utility function for comparing things + * Works for numbers, strings and booleans * Assumes type checking was already done (a and b already have the same type) */ -function compareNumbersAndStrings (a, b) { +function compareNSB (a, b) { if (a < b) { return -1; } if (a > b) { return 1; } return 0; @@ -153,12 +154,16 @@ function compareThings (a, b) { if (b === null) { return a === null ? 0 : 1; } // Numbers - if (typeof a === 'number') { return typeof b === 'number' ? compareNumbersAndStrings(a, b) : -1; } - if (typeof b === 'number') { return typeof a === 'number' ? compareNumbersAndStrings(a, b) : 1; } + if (typeof a === 'number') { return typeof b === 'number' ? compareNSB(a, b) : -1; } + if (typeof b === 'number') { return typeof a === 'number' ? compareNSB(a, b) : 1; } // Strings - if (typeof a === 'string') { return typeof b === 'string' ? compareNumbersAndStrings(a, b) : -1; } - if (typeof b === 'string') { return typeof a === 'string' ? compareNumbersAndStrings(a, b) : 1; } + if (typeof a === 'string') { return typeof b === 'string' ? compareNSB(a, b) : -1; } + if (typeof b === 'string') { return typeof a === 'string' ? compareNSB(a, b) : 1; } + + // Booleans + if (typeof a === 'boolean') { return typeof b === 'boolean' ? compareNSB(a, b) : -1; } + if (typeof b === 'boolean') { return typeof a === 'boolean' ? compareNSB(a, b) : 1; } } diff --git a/test/model.test.js b/test/model.test.js index cdcfdf8..8c00017 100644 --- a/test/model.test.js +++ b/test/model.test.js @@ -379,6 +379,24 @@ describe('Model', function () { }); }); + it('Then booleans', function () { + var otherStuff = [new Date(4321), {}, { hello: 'world' }, [], ['quite', 5]] + , bools = [true, false]; + + model.compareThings(true, true).should.equal(0); + model.compareThings(false, false).should.equal(0); + model.compareThings(true, false).should.equal(1); + model.compareThings(false, true).should.equal(-1); + + otherStuff.forEach(function (stuff) { + bools.forEach(function (bool) { + model.compareThings(bool, stuff).should.equal(-1); + model.compareThings(stuff, bool).should.equal(1); + }); + }); + }); + + }); // ==== End of 'Comparing things' ==== //