diff --git a/src/replacers/__tests__/operation.test.js b/src/replacers/__tests__/operation.test.js index aa9d0ba..f840eab 100644 --- a/src/replacers/__tests__/operation.test.js +++ b/src/replacers/__tests__/operation.test.js @@ -17,8 +17,13 @@ describe('operation', function () { expect(operation.isOperation('$abc-100%')).toEqual({operator: '-', v1: '$abc', v2: '100%'}); }); + it('should detect /', function () { + expect(operation.isOperation('10 / 20')).toEqual({operator: '/', v1: '10', v2: '20'}); + expect(operation.isOperation('$abc/100%')).toEqual({operator: '/', v1: '$abc', v2: '100%'}); + }); + it('should return false for non-operation', function () { - expect(operation.isOperation('$abc/100%')).toBe(false); + expect(operation.isOperation('$abc^100%')).toBe(false); }); it('should exec *', function () { @@ -33,11 +38,17 @@ describe('operation', function () { expect(operation.exec({operator: '-', v1: 10, v2: 0.5})).toBe(9.5); }); + it('should exec /', function () { + expect(operation.exec({operator: '/', v1: 10, v2: 0.5})).toBe(20); + }); + it('should throw on invalid data', function () { expect(() => operation.exec({operator: 'a', v1: 10, v2: 0.5})) .toThrowError('Unknown operator: a'); expect(() => operation.exec({operator: '+', v1: '10', v2: 0.5})) .toThrowError('Operation value should be number, you try: 10'); + expect(() => operation.exec({operator: '/', v1: 10, v2: 0})) + .toThrowError('Operation divisor should not be zero'); expect(() => operation.exec({operator: '+', v1: 10, v2: null})) .toThrowError('Operation value should be number, you try: null'); }); diff --git a/src/replacers/operation.js b/src/replacers/operation.js index 0da2c7b..bdb7f12 100644 --- a/src/replacers/operation.js +++ b/src/replacers/operation.js @@ -7,6 +7,7 @@ const operators = { '*': (v1, v2) => v1 * v2, '+': (v1, v2) => v1 + v2, '-': (v1, v2) => v1 - v2, + '/': (v1, v2) => v1 / v2, }; export default { @@ -38,6 +39,9 @@ function exec(opInfo) { assertOperator(opInfo.operator); assertValue(opInfo.v1); assertValue(opInfo.v2); + if (opInfo.operator === '/') { + assertDivisor(opInfo.v2); + } let fn = operators[opInfo.operator]; return fn(opInfo.v1, opInfo.v2); } @@ -62,3 +66,9 @@ function assertValue(value) { throw new Error('Operation value should be number, you try: ' + value); } } + +function assertDivisor(divisor) { + if (divisor === 0) { + throw new Error('Operation divisor should not be zero'); + } +}