DEV Community

Discussion on: Write a script to find "Happy Numbers"

Collapse
prodigalknight profile image
RevanProdigalKnight • Edited on

Your code in ES2016+ (and a bit less readable):

const isHappy = n => {
  if (n === 4) return false;

  const u = [...n.toString()].reduce((ac, c) => ac + (c ** 2), 0);

  return u === 1 || isHappy(u);
};
Collapse
nickytonline profile image
Nick Taylor (he/him)

You could even shorten the toString by replacing it with a template string which will do an implicit toString.

const isHappy = n => {
  if (n === 4) return false;

  const u = [...`${n}`].reduce((ac, c) => ac + (c ** 2), 0);

  return u === 1 || isHappy(u);
};