Fixed HexToDecConverter file name and added tests; made conversion from

binary and hexadecimal to decimal stricter.
This commit is contained in:
Manuel Friedli 2018-08-31 23:59:52 +02:00
parent e8f5d12fda
commit 8280e0be94
5 changed files with 20 additions and 4 deletions

View File

@ -4,7 +4,7 @@ import {BinToDecConverter} from './converter/bin-to-dec-converter';
import {Converter} from './converter/converter';
import {DecToBinConverter} from './converter/dec-to-bin-converter';
import {DecToHexConverter} from './converter/dec-to-hex-converter';
import {HexToDecConverter} from './converter/hextodecconverter';
import {HexToDecConverter} from './converter/hex-to-dec-converter';
import {HTMLEntitiesDecoder} from './converter/htmlentitiesdecoder';
import {HTMLEntitiesEncoder} from './converter/htmlentitiesencoder';
import {Injectable} from '@angular/core';

View File

@ -11,6 +11,6 @@ describe('BinToDecConverter', () => {
expect(new BinToDecConverter().convert('11011')).toEqual('27');
});
it('should raise an exception on invalid input', () => {
expect(() => new BinToDecConverter().convert('foo bar')).toThrowError('The input seems not to be a valid binary number.');
expect(() => new BinToDecConverter().convert('1foo bar')).toThrowError('The input seems not to be a valid binary number.');
});
});

View File

@ -11,7 +11,7 @@ export class BinToDecConverter implements Converter {
convert(input: string): string {
const n: number = parseInt(input, 2);
if (isNaN(n)) {
if (isNaN(n) || !input.trim().match(/^([01]+)$/)) {
throw new Error('The input seems not to be a valid binary number.');
}
return n.toString(10);

View File

@ -0,0 +1,16 @@
import {HexToDecConverter} from './hex-to-dec-converter';
describe('HexToDecConverter', () => {
it('should create an instance', () => {
expect(new HexToDecConverter()).toBeTruthy();
});
it('should have the id "hextodec"', () => {
expect(new HexToDecConverter().getId()).toEqual('hextodec');
});
it('should convert "ab" to "171"', () => {
expect(new HexToDecConverter().convert('ab')).toEqual('171');
});
it('should raise an exception on invalid input', () => {
expect(() => new HexToDecConverter().convert('foo bar')).toThrowError('The input seems not to be a valid hexadecimal number.');
});
});

View File

@ -11,7 +11,7 @@ export class HexToDecConverter implements Converter {
convert(input: string): string {
const n: number = parseInt(input, 16);
if (isNaN(n)) {
if (isNaN(n) || !input.trim().match(/^((0x|0X)?[0-9a-fA-F]+)$/)) {
throw new Error('The input seems not to be a valid hexadecimal number.');
}
return n.toString(10);