fromNumber, toNumber, fromString, toString

...like the rest of the library.
This commit is contained in:
Ryan X. Charles 2014-08-31 20:38:39 -07:00
parent 6ffb6574ed
commit a0150f82ef
2 changed files with 57 additions and 1 deletions

View File

@ -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];
};

View File

@ -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() {