From 46691bb299f6cea46fcf07bd8c3d3568d8e0044a Mon Sep 17 00:00:00 2001 From: orangegrove_1955 Date: Tue, 4 Oct 2022 10:46:11 +1100 Subject: [PATCH] Added AbsoluteValue and its associated tests --- Maths/AbsoluteValue.ts | 16 ++++++++++++++++ Maths/test/AbsoluteValue.test.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 Maths/AbsoluteValue.ts create mode 100644 Maths/test/AbsoluteValue.test.ts diff --git a/Maths/AbsoluteValue.ts b/Maths/AbsoluteValue.ts new file mode 100644 index 00000000..9451887a --- /dev/null +++ b/Maths/AbsoluteValue.ts @@ -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; +}; diff --git a/Maths/test/AbsoluteValue.test.ts b/Maths/test/AbsoluteValue.test.ts new file mode 100644 index 00000000..7626382d --- /dev/null +++ b/Maths/test/AbsoluteValue.test.ts @@ -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); + }); +});