Browse Source

fromNumber, toNumber, fromString, toString

...like the rest of the library.
patch-2
Ryan X. Charles 11 years ago
parent
commit
a0150f82ef
  1. 18
      lib/opcode.js
  2. 40
      test/opcode.js

18
lib/opcode.js

@ -1,8 +1,12 @@
function Opcode(num) {
if (!(this instanceof Opcode))
return new Opcode(num);
if (typeof num === 'number') {
this.num = num;
} else if (typeof num === 'string') {
var str = num;
this.num = Opcode.map[str];
} else if (num) {
var obj = num;
this.set(obj);
@ -14,6 +18,20 @@ Opcode.prototype.set = function(obj) {
return this;
};
Opcode.prototype.fromNumber = function(num) {
this.num = num;
return this;
};
Opcode.prototype.toNumber = function() {
return this.num;
};
Opcode.prototype.fromString = function(str) {
this.num = Opcode.map[str];
return this;
};
Opcode.prototype.toString = function() {
return Opcode.reverseMap[this.num];
};

40
test/opcode.js

@ -9,8 +9,46 @@ describe('Opcode', function() {
it('should convert to a string with this handy syntax', function() {
Opcode(0).toString().should.equal('OP_0');
Opcode(97).toString().should.equal('OP_NOP');
Opcode(96).toString().should.equal('OP_16');
Opcode(97).toString().should.equal('OP_NOP');
});
it('should convert to a number with this handy syntax', function() {
Opcode('OP_0').toNumber().should.equal(0);
Opcode('OP_16').toNumber().should.equal(96);
Opcode('OP_NOP').toNumber().should.equal(97);
});
describe('#fromNumber', function() {
it('should work for 0', function() {
Opcode().fromNumber(0).num.should.equal(0);
});
});
describe('#toNumber', function() {
it('should work for 0', function() {
Opcode().fromNumber(0).toNumber().should.equal(0);
});
});
describe('#fromString', function() {
it('should work for OP_0', function() {
Opcode().fromString('OP_0').num.should.equal(0);
});
});
describe('#toString', function() {
it('should work for OP_0', function() {
Opcode().fromString('OP_0').toString().should.equal('OP_0');
});
});
describe('@map', function() {

Loading…
Cancel
Save