diff --git a/lib/opcode.js b/lib/opcode.js index 6091c7b..417213d 100644 --- a/lib/opcode.js +++ b/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]; }; diff --git a/test/opcode.js b/test/opcode.js index 843b6f4..e531c9a 100644 --- a/test/opcode.js +++ b/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() {