Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Maths/AbsoluteValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* @function AbsoluteValue
* @description Calculate the absolute value of an input number.
* @param {number} number - a numeric input value
* @return {number} - Absolute number of input number
* @see https://en.wikipedia.org/wiki/Absolute_value
* @example AbsoluteValue(-10) = 10
* @example AbsoluteValue(50) = 50
* @example AbsoluteValue(0) = 0
*/

export const AbsoluteValue = (number: number): number => {
// if input number is less than 0, convert it to positive via double negation
// e.g. if n = -2, then return -(-2) = 2
return number < 0 ? -number : number;
};
28 changes: 28 additions & 0 deletions Maths/test/AbsoluteValue.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { AbsoluteValue } from "../AbsoluteValue";

describe("AbsoluteValue", () => {
it("should return the absolute value of zero", () => {
const absoluteValueOfZero = AbsoluteValue(0);
expect(absoluteValueOfZero).toBe(0);
});

it("should return the absolute value of a negative integer", () => {
const absoluteValueOfNegativeInteger = AbsoluteValue(-34);
expect(absoluteValueOfNegativeInteger).toBe(34);
});

it("should return the absolute value of a positive integer", () => {
const absoluteValueOfPositiveInteger = AbsoluteValue(50);
expect(absoluteValueOfPositiveInteger).toBe(50);
});

it("should return the absolute value of a positive floating number", () => {
const absoluteValueOfPositiveFloating = AbsoluteValue(20.2034);
expect(absoluteValueOfPositiveFloating).toBe(20.2034);
});

it("should return the absolute value of a negative floating number", () => {
const absoluteValueOfNegativeFloating = AbsoluteValue(-20.2034);
expect(absoluteValueOfNegativeFloating).toBe(20.2034);
});
});