Skip to content

Commit c5a2566

Browse files
bug: abs returns 0 on an empty array (TheAlgorithms#1473)
* bug: update edge case for empty array * bug: add edge case for empty arrays * feat: add test case for empty array --------- Co-authored-by: Ridge Kimani <ridgekimani@gmail.com>
1 parent 52858f8 commit c5a2566

File tree

2 files changed

+3
-2
lines changed

2 files changed

+3
-2
lines changed

Maths/Abs.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@
1212
const abs = (num) => {
1313
const validNumber = +num // converted to number, also can use - Number(num)
1414

15-
if (Number.isNaN(validNumber)) {
15+
if (Number.isNaN(validNumber) || typeof num === 'object') {
1616
throw new TypeError('Argument is NaN - Not a Number')
1717
}
1818

19-
return validNumber < 0 ? -validNumber : validNumber // if number is less then zero mean negative then it converted to positive. i.e -> n = -2 = -(-2) = 2
19+
return validNumber < 0 ? -validNumber : validNumber // if number is less than zero mean negative then it converted to positive. i.e -> n = -2 = -(-2) = 2
2020
}
2121

2222
export { abs }

Maths/test/Abs.test.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ describe('Testing abs function', () => {
55
expect(() => abs('234a')).toThrow()
66
expect(() => abs({})).toThrow()
77
expect(() => abs([12, -32, -60])).toThrow()
8+
expect(() => abs([])).toThrow() // coerces to 0
89
})
910

1011
it('Testing for number of string type', () => {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy