Skip to content

Commit e73decf

Browse files
fix: handle negative zero in absoluteValue
1 parent 5c39e87 commit e73decf

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

‎Maths/AbsoluteValue.js‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @function absoluteValue
3+
* @description Returns the absolute value of a number without using
4+
* JavaScript's built-in Math.abs() function.
5+
* @param {number} n - Any real number
6+
* @returns {number} - The absolute value of n
7+
* @see https://en.wikipedia.org/wiki/Absolute_value
8+
* @example absoluteValue(-5) => 5
9+
* @example absoluteValue(3) => 3
10+
* @example absoluteValue(0) => 0
11+
*/
12+
const absoluteValue = (n) => {
13+
if (typeof n !== 'number' || isNaN(n)) {
14+
throw new TypeError('Input must be a number')
15+
}
16+
return n < 0 ? -n : n === 0 ? 0 : n
17+
}
18+
19+
export { absoluteValue }

‎Maths/test/AbsoluteValue.test.js‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { absoluteValue } from '../AbsoluteValue.js'
2+
3+
describe('absoluteValue', () => {
4+
test('absoluteValue(-5) returns 5', () => {
5+
expect(absoluteValue(-5)).toBe(5)
6+
})
7+
8+
test('absoluteValue(3) returns 3', () => {
9+
expect(absoluteValue(3)).toBe(3)
10+
})
11+
12+
test('absoluteValue(0) returns 0', () => {
13+
expect(absoluteValue(0)).toBe(0)
14+
})
15+
16+
test('absoluteValue(-99.99) returns 99.99', () => {
17+
expect(absoluteValue(-99.99)).toBe(99.99)
18+
})
19+
20+
test('absoluteValue(100) returns 100', () => {
21+
expect(absoluteValue(100)).toBe(100)
22+
})
23+
24+
test('throws TypeError for non-number input', () => {
25+
expect(() => absoluteValue('abc')).toThrow(TypeError)
26+
})
27+
28+
test('throws TypeError for NaN', () => {
29+
expect(() => absoluteValue(NaN)).toThrow(TypeError)
30+
})
31+
})

0 commit comments

Comments
 (0)