Skip to content

Commit

Permalink
Adding subtract method
Browse files Browse the repository at this point in the history
  • Loading branch information
dinoknowsbetter committed Aug 5, 2024
1 parent 9e3f6b5 commit 7114eb8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/lib/hypermath.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
Expand Down Expand Up @@ -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');
});
});
});
16 changes: 16 additions & 0 deletions src/lib/hypermath.ts
Original file line number Diff line number Diff line change
@@ -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');
Expand Down Expand Up @@ -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;
}
}

0 comments on commit 7114eb8

Please sign in to comment.