Last active
August 29, 2015 13:56
-
-
Save sidazhang/8813156 to your computer and use it in GitHub Desktop.
pure js buffertool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Buffer = require('buffer').Buffer | |
// compare equivalence 0 is true 1 is false | |
Buffer.prototype.compare = function(buf) { | |
if (!Buffer.isBuffer(buf)) { | |
buf = new Buffer(buf) | |
} | |
if (this.length !== buf.length) { | |
return 1 | |
} | |
for (var i = 0; i < this.length; i++) { | |
if (this[i] !== buf[i]) { | |
return 1 | |
} | |
} | |
return 0 | |
} | |
Buffer.prototype.reverse = function() { | |
if (this.length <= 1) { | |
return | |
} | |
var left; | |
var right; | |
var length = this.length; | |
for (left = 0, right = length - 1; left < right; left += 1, right -= 1) { | |
var tmp = this[left]; | |
this[left] = this[right]; | |
this[right] = tmp; | |
} | |
} | |
var a = new Buffer([1, 2, 3]); | |
var b = new Buffer([1, 2, 3]); | |
console.log('#compare() - should pass', a.compare(b) === 0); | |
var a1 = new Buffer([1, 2, 3, 4]); | |
var b1 = new Buffer([1, 2, 3]); | |
console.log('#compare() (different length) - should fail', a1.compare(b1) === 1); | |
var a2 = new Buffer([1, 2, 4]); | |
var b2 = new Buffer([1, 2, 3]); | |
console.log('#compare() (same length but different) - should fail', a2.compare(b2) === 1); | |
var a3 = new Buffer([1, 2, 4]); | |
var b3 = [1, 2, 4]; | |
console.log('#compare() (not a buffer) - should convert to buffer and pass', a3.compare(b3) === 0); | |
var a4 = new Buffer('live') | |
var b4 = 'live' | |
console.log('#compare() (string) - should pass', a4.compare(b4) === 0) | |
a.reverse(); | |
var aReversed = new Buffer([3, 2, 1]); | |
console.log('#reverse() with 3 items (odd number) - should pass', a.compare(aReversed) === 0) | |
var d = new Buffer([1, 2, 3, 4]) | |
var dReversed = new Buffer([4, 3, 2, 1]) | |
d.reverse(); | |
console.log('#reverse() with 4 item (even number) - should pass', d.compare(dReversed) === 0) | |
var c = new Buffer([1]) | |
var cReversed = new Buffer([1]) | |
c.reverse(); | |
console.log('#reverse() with 1 item (nothing should happen) - should pass', c.compare(cReversed) === 0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment