support of negative values

This commit is contained in:
Borys Levytskyi
2015-04-11 23:46:56 +03:00
parent 491141e618
commit b7ea2545bb
3 changed files with 21 additions and 5 deletions

View File

@@ -5,6 +5,9 @@ app.set('calc', function() {
return { return {
numberOfBits: function (num) { numberOfBits: function (num) {
if(num < 0) {
return 32;
}
should.bePositiveInteger(num); should.bePositiveInteger(num);
return Math.floor(Math.log(num) / Math.log(2)) + 1; return Math.floor(Math.log(num) / Math.log(2)) + 1;
}, },

View File

@@ -1,8 +1,8 @@
app.set('expression', function() { app.set('expression', function() {
"use strict"; "use strict";
var exprRegex = /^(\d+|0x[\d,a-f]+)\s*(<<|>>|\||\&|\^)\s*(\d+|0x[\d,a-f]+)$/; var exprRegex = /^(-?(?:\d+|0x[\d,a-f]+))\s*(<<|>>|\||\&|\^)\s*(-?(?:\d+|0x[\d,a-f]+))$/;
var listRegex = /^((\d+|0x[\d,a-f]+)\s?)+$/ var listRegex = /^(-?(?:\d+|0x[\d,a-f]+)\s?)+$/;
return { return {
canParse: function(string) { canParse: function(string) {
@@ -73,10 +73,11 @@ app.set('expression', function() {
this.input = input; this.input = input;
this.value = parseInt(input); this.value = parseInt(input);
// console.log('value: ' + this.value); // console.log('value: ' + this.value);
this.hex = '0x' + this.value.toString(16); var hex = this.value.toString(16);
this.hex = hex.indexOf('-') == 0 ? '-0x' + hex.substr(1) : '0x' + hex;
this.dec = this.value.toString(10); this.dec = this.value.toString(10);
this.bin = this.value.toString(2); this.bin = (this.value>>>0).toString(2);
this.kind = this.input.indexOf('0x') == 0 ? 'hex' : 'dec'; this.kind = this.input.indexOf('0x') > -1 ? 'hex' : 'dec';
this.other = this.kind == 'dec' ? this.hex : this.dec; this.other = this.kind == 'dec' ? this.hex : this.dec;
} }

View File

@@ -36,6 +36,7 @@ describe("expression parse", function() {
}); });
var listCases = { var listCases = {
'-0xa -9' : [-10, -9],
'1 2 3': [1, 2, 3], '1 2 3': [1, 2, 3],
'0x1 2 0xa6b': [0x1, 2, 0xa6b], '0x1 2 0xa6b': [0x1, 2, 0xa6b],
'0x11a': [0x11a] '0x11a': [0x11a]
@@ -68,6 +69,17 @@ describe('create operands', function() {
rundOperandsTest(hexOperand, decOperand); rundOperandsTest(hexOperand, decOperand);
}); });
describe('negative operands', function () {
var op = expression.parseOperand('-0xa');
it('shoold have correct values', function() {
expect(op.value).toBe(-10);
expect(op.hex).toBe('-0xa');
expect(op.bin).toBe('11111111111111111111111111110110');
expect(op.dec).toBe('-10');
expect(op.kind).toBe('hex');
})
});
function rundOperandsTest(hexOperand, decOperand) { function rundOperandsTest(hexOperand, decOperand) {
it('should remember input form', function() { it('should remember input form', function() {
expect(hexOperand.input).toBe('0x10'); expect(hexOperand.input).toBe('0x10');