Skip to content
Closed
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
17 changes: 17 additions & 0 deletions Maths/FindMax.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Function to find the maximum number given an array of integers
* Returns the maximum number of the array
* If the array is empty it returns the string 'Array is empty'
*/

export const findMax = (arr) => {
if (arr.length === 0) { return 'Array is empty' }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Throw an error, not a string.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree with @raklaptudirm. Whenever you know the conditions where your function will fail (I call them nice errors) then throw then instead of handling them yourself (by returning a string) throw an error instead so that the user can handled them according to their business rules.


let max = arr[0]
arr.forEach(element => {
if (element > max) {
max = element
}
})
return max
}
16 changes: 16 additions & 0 deletions Maths/test/FindMax.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { findMax } from '../FindMax'

test('Should return the highest number in the array', () => {
const max = findMax([2, 5, 1, 12, 43, 1, 9])
expect(max).toBe(43)
})

test('Should return the highest number in the array', () => {
const max = findMax([21, 513, 6])
expect(max).toBe(513)
})

test('Should return the highest number in the array', () => {
const max = findMax([])
expect(max).toBe('Array is empty')
})