diff --git a/Maths/FindMax.js b/Maths/FindMax.js new file mode 100644 index 0000000000..5ff30d7d0a --- /dev/null +++ b/Maths/FindMax.js @@ -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' } + + let max = arr[0] + arr.forEach(element => { + if (element > max) { + max = element + } + }) + return max +} diff --git a/Maths/test/FindMax.test.js b/Maths/test/FindMax.test.js new file mode 100644 index 0000000000..6c39d3dbc2 --- /dev/null +++ b/Maths/test/FindMax.test.js @@ -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') +})