Skip to content

Commit eb8261f

Browse files
Added AbsoluteValue and its associated tests (#31)
1 parent 4d0d714 commit eb8261f

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Maths/AbsoluteValue.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* @function AbsoluteValue
3+
* @description Calculate the absolute value of an input number.
4+
* @param {number} number - a numeric input value
5+
* @return {number} - Absolute number of input number
6+
* @see https://en.wikipedia.org/wiki/Absolute_value
7+
* @example AbsoluteValue(-10) = 10
8+
* @example AbsoluteValue(50) = 50
9+
* @example AbsoluteValue(0) = 0
10+
*/
11+
12+
export const AbsoluteValue = (number: number): number => {
13+
// if input number is less than 0, convert it to positive via double negation
14+
// e.g. if n = -2, then return -(-2) = 2
15+
return number < 0 ? -number : number;
16+
};

Maths/test/AbsoluteValue.test.ts

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { AbsoluteValue } from "../AbsoluteValue";
2+
3+
describe("AbsoluteValue", () => {
4+
it("should return the absolute value of zero", () => {
5+
const absoluteValueOfZero = AbsoluteValue(0);
6+
expect(absoluteValueOfZero).toBe(0);
7+
});
8+
9+
it("should return the absolute value of a negative integer", () => {
10+
const absoluteValueOfNegativeInteger = AbsoluteValue(-34);
11+
expect(absoluteValueOfNegativeInteger).toBe(34);
12+
});
13+
14+
it("should return the absolute value of a positive integer", () => {
15+
const absoluteValueOfPositiveInteger = AbsoluteValue(50);
16+
expect(absoluteValueOfPositiveInteger).toBe(50);
17+
});
18+
19+
it("should return the absolute value of a positive floating number", () => {
20+
const absoluteValueOfPositiveFloating = AbsoluteValue(20.2034);
21+
expect(absoluteValueOfPositiveFloating).toBe(20.2034);
22+
});
23+
24+
it("should return the absolute value of a negative floating number", () => {
25+
const absoluteValueOfNegativeFloating = AbsoluteValue(-20.2034);
26+
expect(absoluteValueOfNegativeFloating).toBe(20.2034);
27+
});
28+
});

0 commit comments

Comments
 (0)