Counting elements of an array using a recursive function in JS

Viewed 1505

I am going through the grokking algorithms book and trying to wrap my head around recursion. One of the challenges in the book is to "Write a recursive function to count the number of items in a list.". I came up with the following code, which works:

function recursiveArrayCount(arr, count) {
  if (arr.length == 0) {
    return 0;
  } else {
    arr.pop();
    return count + recursiveArrayCount(arr, count);
  }
}

let myArray = [1, 10, 23, 11, 4, 48, 88];
console.log(recursiveArrayCount(myArray, 1));

My question is, is there a better way to do this in javascript? In particular, I don't like having to seed the value of count with the initial '1' - but I can't think of another way to do it.

2 Answers

You don't need a second argument at all:

function recursiveArrayCount(arr) {
    if (arr.length == 0) {
        return 0;
    }
    return 1 + recursiveArrayCount(arr.slice(1));
}

Make a proper tail call by eliminating any reference to variables that would be needed after the recursive call returns.

function recursiveArrayCount(arr) {
  return _recursiveCount(arr, 0);

  function _recursiveCount(arr, count) {
    return arr.length == 0 ? count : _recursiveCount(arr.slice(1), count + 1);
  }
}

let myArray = [1, 10, 23, 11, 4, 48, 88];
console.log(recursiveArrayCount(myArray));

This makes it more likely to be optimized by reusing stack space.

Also, I used a nested function for the recursion, which ensures that the count is properly initialized.


You could also get a little fancy with the inner function, like this:

function recursiveArrayCount(arr) {
  return (function _recursiveCount(arr, count) {
    return arr.length == 0 ? count : _recursiveCount(arr.slice(1), count + 1);
  })(arr, 0);
}

let myArray = [1, 10, 23, 11, 4, 48, 88];
console.log(recursiveArrayCount(myArray));

It's a recursively invoked IIFE.

Related