diff --git a/Int64.js b/Int64.js index d394c4a..f870a2a 100644 --- a/Int64.js +++ b/Int64.js @@ -235,6 +235,13 @@ Int64.prototype = { * @param {Int64} other Other Int64 to compare. */ compare: function(other) { + + // If sign bits differ ... + if ((this.buffer[this.offset] & 0x80) != (other.buffer[other.offset] & 0x80)) { + return other.buffer[other.offset] - this.buffer[this.offset]; + } + + // otherwise, compare bytes lexicographically for (var i = 0; i < 8; i++) { if (this.buffer[this.offset+i] !== other.buffer[other.offset+i]) { return this.buffer[this.offset+i] - other.buffer[other.offset+i]; @@ -243,6 +250,15 @@ Int64.prototype = { return 0; }, + /** + * Returns a boolean indicating if this integer is equal to other. + * + * @param {Int64} other Other Int64 to compare. + */ + equals: function(other) { + return this.compare(other) === 0; + }, + /** * Pretty output in console.log */ diff --git a/test.js b/test.js index 1187364..cdf4303 100644 --- a/test.js +++ b/test.js @@ -81,3 +81,40 @@ exports.testBufferOffsets = function(test) { test.done(); }; + +exports.testInstanceOf = function(test) { + var x = new Int64(); + assert(x instanceof Int64, 'Variable is not instance of Int64'); + var y = {}; + assert(!(y instanceof Int64), 'Object is an instance of Int64'); + test.done(); +}; + +exports.testCompare = function(test) { + var intMin = new Int64(2147483648, 0); + var intMinPlusOne = new Int64(2147483648, 1); + var zero = new Int64(0, 0); + var intMaxMinusOne = new Int64(2147483647, 4294967294); + var intMax = new Int64(2147483647, 4294967295); + assert(intMin.compare(intMinPlusOne) < 0, "INT64_MIN is not less than INT64_MIN+1"); + assert(intMin.compare(zero) < 0, "INT64_MIN is not less than 0"); + assert(intMin.compare(zero) < intMax, "INT64_MIN is not less than INT64_MAX"); + assert(intMax.compare(intMaxMinusOne) > 0, "INT64_MAX is not greater than INT64_MAX-1"); + assert(intMax.compare(zero) > 0, "INT64_MAX is not greater than 0"); + assert(intMax.compare(intMin) > 0, "INT64_MAX is not greater than INT_MIN"); + test.done(); +}; + +exports.testEquals = function(test) { + var intMin = new Int64(2147483648, 0); + var zero = new Int64(0, 0); + var intMax = new Int64(2147483647, 4294967295); + assert(intMin.equals(intMin), "INT64_MIN !== INT64_MIN"); + assert(intMax.equals(intMax), "INT64_MAX !== INT64_MAX"); + assert(zero.equals(zero), "0 !== 0"); + assert(!intMin.equals(zero), "INT64_MIN === 0"); + assert(!intMin.equals(intMax), "INT64_MIN === INT64_MAX"); + assert(!intMax.equals(zero), "INT64_MAX === 0"); + assert(!intMax.equals(intMin), "INT64_MAX === INT64_MIN"); + test.done(); +};