From a0150f82ef11659ae07f12bbcbef7ecb9e97509b Mon Sep 17 00:00:00 2001 From: "Ryan X. Charles" Date: Sun, 31 Aug 2014 20:38:39 -0700 Subject: [PATCH] fromNumber, toNumber, fromString, toString ...like the rest of the library. --- lib/opcode.js | 18 ++++++++++++++++++ test/opcode.js | 40 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/lib/opcode.js b/lib/opcode.js index 6091c7bc6..417213d82 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 843b6f471..e531c9a27 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() {