Skip to content

Commit 7114eb8

Browse files
Adding subtract method
1 parent 9e3f6b5 commit 7114eb8

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/lib/hypermath.spec.ts

+24-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ describe('HyperMath', () => {
1919

2020
it('should throw an error if the input is invalid', () => {
2121
expect(() => {
22-
HyperMath.multiply('abc', 3);
22+
HyperMath.multiply('abc', null);
2323
}).toThrow('Invalid input');
2424
});
2525
});
@@ -69,4 +69,27 @@ describe('HyperMath', () => {
6969
}).toThrow('Invalid input');
7070
});
7171
});
72+
73+
describe('subtract', () => {
74+
it('should subtract two numbers correctly', () => {
75+
const result = HyperMath.subtract(7, 5);
76+
expect(result).toBe(2);
77+
});
78+
79+
it('should subtract two values with decimals correctly', () => {
80+
const result = HyperMath.subtract(8.5, '3.3');
81+
expect(result).toBe(5.2);
82+
});
83+
84+
it('should subtract two strings that represent numbers correctly', () => {
85+
const result = HyperMath.subtract('9', '5');
86+
expect(result).toBe(4);
87+
});
88+
89+
it('should throw an error if the input is invalid', () => {
90+
expect(() => {
91+
HyperMath.subtract(undefined, 3);
92+
}).toThrow('Invalid input');
93+
});
94+
});
7295
});

src/lib/hypermath.ts

+16
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
export class HyperMath {
22
static processInput(value: number | string): number {
3+
if (!value) {
4+
throw new Error('Invalid input');
5+
}
36
if (typeof value === 'string') {
47
if (isNaN(parseInt(value))) {
58
throw new Error('Invalid input');
@@ -47,4 +50,17 @@ export class HyperMath {
4750
result = parseFloat(result.toPrecision(2));
4851
return result;
4952
}
53+
54+
public static subtract(
55+
firstValue: number | string,
56+
secondValue: number | string,
57+
): number {
58+
let a = this.processInput(firstValue);
59+
let b = this.processInput(secondValue);
60+
let numberOne = parseFloat(a.toPrecision(2));
61+
let numberTwo = parseFloat(b.toPrecision(2));
62+
let result = numberOne - numberTwo;
63+
result = parseFloat(result.toPrecision(2));
64+
return result;
65+
}
5066
}

0 commit comments

Comments
 (0)