diff --git a/src/lib/hypermath.spec.ts b/src/lib/hypermath.spec.ts index aff9d17..d5e1086 100644 --- a/src/lib/hypermath.spec.ts +++ b/src/lib/hypermath.spec.ts @@ -19,7 +19,7 @@ describe('HyperMath', () => { it('should throw an error if the input is invalid', () => { expect(() => { - HyperMath.multiply('abc', 3); + HyperMath.multiply('abc', null); }).toThrow('Invalid input'); }); }); @@ -69,4 +69,27 @@ describe('HyperMath', () => { }).toThrow('Invalid input'); }); }); + + describe('subtract', () => { + it('should subtract two numbers correctly', () => { + const result = HyperMath.subtract(7, 5); + expect(result).toBe(2); + }); + + it('should subtract two values with decimals correctly', () => { + const result = HyperMath.subtract(8.5, '3.3'); + expect(result).toBe(5.2); + }); + + it('should subtract two strings that represent numbers correctly', () => { + const result = HyperMath.subtract('9', '5'); + expect(result).toBe(4); + }); + + it('should throw an error if the input is invalid', () => { + expect(() => { + HyperMath.subtract(undefined, 3); + }).toThrow('Invalid input'); + }); + }); }); diff --git a/src/lib/hypermath.ts b/src/lib/hypermath.ts index b67d6dc..4612558 100644 --- a/src/lib/hypermath.ts +++ b/src/lib/hypermath.ts @@ -1,5 +1,8 @@ export class HyperMath { static processInput(value: number | string): number { + if (!value) { + throw new Error('Invalid input'); + } if (typeof value === 'string') { if (isNaN(parseInt(value))) { throw new Error('Invalid input'); @@ -47,4 +50,17 @@ export class HyperMath { result = parseFloat(result.toPrecision(2)); return result; } + + public static subtract( + firstValue: number | string, + secondValue: number | string, + ): number { + let a = this.processInput(firstValue); + let b = this.processInput(secondValue); + let numberOne = parseFloat(a.toPrecision(2)); + let numberTwo = parseFloat(b.toPrecision(2)); + let result = numberOne - numberTwo; + result = parseFloat(result.toPrecision(2)); + return result; + } }