Last active
February 8, 2023 17:26
-
-
Save daftAnorak/527616c2d1cbce3e84e3ef6fe63695c9 to your computer and use it in GitHub Desktop.
Code Exercise for JS Position - Magic Numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Method which takes a given, natural number and calculates | |
* a series of magic numbers until a number repeats (returns false), | |
* or equals 1 (returns true). | |
* | |
* EX: fn(1) === true // (1 equals 1) | |
* EX: fn(7) === true // (7 -> 49 -> 97 -> 130 -> 10 -> 1) | |
* EX: fn(11) === false // (11 -> 2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 [repeat]) | |
* | |
* @param {number} x - given, natural number | |
* @returns {boolean} whether the magic numbers repeat (false) OR return 1 (true) | |
*/ | |
function magicNumbers(x) { | |
const prevMagicNumbers = new Set(); | |
while (x !== 1) { | |
prevMagicNumbers.add(x); | |
x = String(x).split('').reduce((a, b) => a + b * b, 0); | |
if (prevMagicNumbers.has(x)) return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment