Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Added FindMax to Maths #831

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
JadenLeake333 wants to merge 7 commits into TheAlgorithms:master from JadenLeake333:findMax
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
View file Open in desktop
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

@raklaptudirm raklaptudirm Nov 2, 2021

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

@tjgurwara99 tjgurwara99 Nov 7, 2021

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
View file Open in desktop
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')
})

AltStyle によって変換されたページ (->オリジナル) /