Hone

Lessons · JavaScript · a function that calls itself

A problem defined by a smaller version of itself

A function that calls itself on a smaller input, with a base case that stops it.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Nested components, folder trees, JSON of unknown depth, permutations: structures that contain themselves are natural to walk recursively.

How to think about it

Two questions: what is the smallest case I just know (base)? And given the answer for a smaller input, how do I build this one (step)?

Worked example

function depth(node) {
Depth of a nested list.
  if (!Array.isArray(node)) return 0;
Base: a plain value has depth 0.
  return 1 + Math.max(0, ...node.map(depth));
Step: one more than the deepest child.
}

Your turn

Sum an array recursively.

function total(xs) {
  if (xs.length === 0) return 0;
  return xs[0] + total(xs.slice());
}

The trap

No base case, or a step that does not shrink: 'Maximum call stack size exceeded'.

Practise a function that calls itself on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.