Skip to content

Instantly share code, notes, and snippets.

@YozhEzhi
Last active April 10, 2017 17:04
Show Gist options
  • Save YozhEzhi/af0e5a25b13059a03b81bed947b41cbc to your computer and use it in GitHub Desktop.
Save YozhEzhi/af0e5a25b13059a03b81bed947b41cbc to your computer and use it in GitHub Desktop.
Recursive actions with array
const myArr = [1, 2, 5, 4, 7];
// Recursive sum:
function sum(arr) {
if (arr.length === 0) return 0;
return arr[0] + sum(arr.slice(1));
}
console.log(sum(myArr)); // 19
// Recursive array items count:
function arrayItemsCount(arr) {
if (!arr.length) return 0;
return 1 + arrayItemsCount(arr.slice(1));
}
console.log(arrayItemsCount(myArr)); // 5
// Recursive find biggest item:
function biggestItem(arr) {
if (arr.length === 2) return arr[0] > arr[1] ? arr[0] : arr[1];
const subMax = biggestItem(arr.slice(1));
return arr[0] > subMax ? arr[0] : subMax;
}
console.log(biggestItem(myArr)); // 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment