isHappy

    0

    0

    YusifHasanov

    The code creates a function called isHappy that takes a number as an input and checks to see if that number is equal to the sum of the number's digits. If the number is equal to the sum, the function returns true; otherwise, it returns false.

    const isHappy = (n) => {
      let copy = n, allSums = [], result = false;
      while (!allSums.find(item => item === sum(copy))) {
        if (sum(copy) === 1) {
          result = true;
          break;
        }
        allSums.push(sum(copy))
        copy=sum(copy);
      }
    
      return result;
    };
    
    
    const sum = (number) => {
      let sum=0;
      while (number != 0) {         
        sum+=(number % 10)*(number % 10)
        number = Math.trunc(number / 10);
      }
      return sum
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.