Given an array of numbers, you need to find the largest number in the array. The function should handle various scenarios, including arrays with negative numbers, floating-point numbers, and edge cases like empty arrays or invalid inputs.
Input: array = [1, 5, 3, 7, 2]
Output: 7
Input: array = []
Output: ❌ Throw error => Input is not a valid array or array is empty
Input: string = "aman"
Output: ❌ Throw error => Input is not a valid array or array is empty
Input: array = [-5, 8, 9, 20]
Output: 20
function findLargestNumber(nums) {
if (!Array.isArray(nums) || nums.length === 0) {
throw new Error('Input is not a valid array or array is empty');
}
return Math.max(...nums);
}function findLargestNumberReduce(nums) {
if (!Array.isArray(nums) || nums.length === 0) {
throw new Error('Input is not a valid array or array is empty');
}
return nums.reduce((max, current) => {
if (current > max) {
return current;
}
return max;
}, nums[0]);
}function findLargestNumberLoop(nums) {
if (!Array.isArray(nums) || nums.length === 0) {
throw new Error('Input is not a valid array or array is empty');
}
let largest = nums[0];
for (let i = 1; i < nums.length; i++) {
if (nums[i] > largest) {
largest = nums[i];
}
}
return largest;
}function findLargestNumberForEach(nums) {
if (!Array.isArray(nums) || nums.length === 0) {
throw new Error('Input is not a valid array or array is empty');
}
let largest = nums[0];
nums.forEach(num => {
if (num > largest) {
largest = num;
}
});
return largest;
}function findLargestNumberSort(nums) {
if (!Array.isArray(nums) || nums.length === 0) {
throw new Error('Input is not a valid array or array is empty');
}
return nums.slice().sort((a, b) => b - a)[0];
}function findLargestNumberApply(nums) {
if (!Array.isArray(nums) || nums.length === 0) {
throw new Error('Input is not a valid array or array is empty');
}
return Math.max.apply(null, nums);
}function findLargestNumberForOf(nums) {
if (!Array.isArray(nums) || nums.length === 0) {
throw new Error('Input is not a valid array or array is empty');
}
let largest = nums[0];
for (const num of nums) {
if (num > largest) {
largest = num;
}
}
return largest;
}function findLargestNumberWhile(nums) {
if (!Array.isArray(nums) || nums.length === 0) {
throw new Error('Input is not a valid array or array is empty');
}
let largest = nums[0];
let index = 1;
while (index < nums.length) {
if (nums[index] > largest) {
largest = nums[index];
}
index++;
}
return largest;
}function findLargestNumberFind(nums) {
if (!Array.isArray(nums) || nums.length === 0) {
throw new Error('Input is not a valid array or array is empty');
}
let largest = nums[0];
nums.find(num => {
if (num > largest) {
largest = num;
}
return false;
});
return largest;
}function findLargestNumberMapReduce(nums) {
if (!Array.isArray(nums) || nums.length === 0) {
throw new Error('Input is not a valid array or array is empty');
}
return nums.map(num => num).reduce((max, current) => current > max ? current : max, nums[0]);
}