Skip to content
Open
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
19 changes: 19 additions & 0 deletions Maths/AbsoluteValue.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* @function absoluteValue
* @description Returns the absolute value of a number without using
* JavaScript's built-in Math.abs() function.
* @param {number} n - Any real number
* @returns {number} - The absolute value of n
* @see https://en.wikipedia.org/wiki/Absolute_value
* @example absoluteValue(-5) => 5
* @example absoluteValue(3) => 3
* @example absoluteValue(0) => 0
*/
const absoluteValue = (n) => {
if (typeof n !== 'number' || isNaN(n)) {
throw new TypeError('Input must be a number')
}
return n < 0 ? -n : n === 0 ? 0 : n
}

export { absoluteValue }
31 changes: 31 additions & 0 deletions Maths/test/AbsoluteValue.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { absoluteValue } from '../AbsoluteValue.js'

describe('absoluteValue', () => {
test('absoluteValue(-5) returns 5', () => {
expect(absoluteValue(-5)).toBe(5)
})

test('absoluteValue(3) returns 3', () => {
expect(absoluteValue(3)).toBe(3)
})

test('absoluteValue(0) returns 0', () => {
expect(absoluteValue(0)).toBe(0)
})

test('absoluteValue(-99.99) returns 99.99', () => {
expect(absoluteValue(-99.99)).toBe(99.99)
})

test('absoluteValue(100) returns 100', () => {
expect(absoluteValue(100)).toBe(100)
})

test('throws TypeError for non-number input', () => {
expect(() => absoluteValue('abc')).toThrow(TypeError)
})

test('throws TypeError for NaN', () => {
expect(() => absoluteValue(NaN)).toThrow(TypeError)
})
})
Loading