From 0292985401df2662bfb75ca8bfc3c2337983d693 Mon Sep 17 00:00:00 2001 From: Aditya Bhargava Date: Fri, 18 Nov 2022 14:18:55 -0600 Subject: [PATCH] cleaner max function, remove unnecessary duplication --- 04_quicksort/ES6/04_recursive-max.js | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/04_quicksort/ES6/04_recursive-max.js b/04_quicksort/ES6/04_recursive-max.js index e967c78..6580e2e 100644 --- a/04_quicksort/ES6/04_recursive-max.js +++ b/04_quicksort/ES6/04_recursive-max.js @@ -2,25 +2,15 @@ * Calculate the largest number * This solution only works for arrays longer than one * @param {Array} array Array of numbers - * @returns {number} The argest number + * @returns {number} The largest number */ -const max = array => { - if (array.length === 2) return array[0] > array[1] ? array[0] : array[1]; +const max = (array) => { + if (array.length === 0) return 0; + if (array.length === 1) { + return array[0]; + } const subMax = max(array.slice(1)); return array[0] > subMax ? array[0] : subMax; }; -/** - * Calculate the largest number - * This solution works for arrays of any length - * @param {Array} array Array of numbers - * @param {number} max Maximum value - * @returns {number} The argest number - */ -const alternativeSolutionMax = (array, max = 0) => - array.length === 0 - ? max - : alternativeSolutionMax(array.slice(1), array[0] > max ? array[0] : max); - console.log(max([1, 5, 10, 25, 16, 1])); // 25 -console.log(alternativeSolutionMax([1, 5, 10, 25, 16, 1])); // 25