From 00b28478ce17b8b6d08b07adc9bb12d1dd153739 Mon Sep 17 00:00:00 2001 From: Poliakov Ilia Date: Sat, 7 Dec 2024 17:44:23 +0400 Subject: [PATCH] Update 04_recursive_max.js with fix for alternative solution (#262) * Update 04_recursive_max.js with fix for alternative solution Current alternative solution works only for arrays of natural numbers and for empty arrays it returns 0 instead of null or Error. This commit fixes these problems. * Considering comments from the author --------- Co-authored-by: Ilia Poliakov --- 04_quicksort/javascript/04_recursive_max.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/04_quicksort/javascript/04_recursive_max.js b/04_quicksort/javascript/04_recursive_max.js index f3c15f9..c51aebf 100644 --- a/04_quicksort/javascript/04_recursive_max.js +++ b/04_quicksort/javascript/04_recursive_max.js @@ -14,12 +14,12 @@ function max(array) { /** * Calculate the largest number - * This solution works for arrays of any length + * This solution works for arrays of any length and returns the smallest possible number for empty arrays * @param {Array} array Array of numbers * @param {number} max Maximum value - * @returns {number} The argest number + * @returns {number} The largest number */ -function alternativeSolutionMax(array, max = 0) { +function alternativeSolutionMax(array, max = Number.MIN_VALUE) { return array.length === 0 ? max : alternativeSolutionMax(array.slice(1), array[0] > max ? array[0] : max); @@ -27,3 +27,6 @@ function alternativeSolutionMax(array, max = 0) { console.log(max([1, 5, 10, 25, 16, 1])); // 25 console.log(alternativeSolutionMax([1, 5, 10, 25, 16, 1])); // 25 + +console.log(max([])); // RangeError: Maximum call stack size exceeded +console.log(alternativeSolutionMax([])); // Number.MIN_VALUE