0
\$\begingroup\$

This is a helper function, along with three others. It should be called as a .filter(); to return only prime numbers. It is for one of the exercises at FreeCodeCamp.com, "Sum all Primes".

I'm just trying to accumulate the charAt(*) for each n, so 10 would return 1, being 1+0 21 would return 3, being 2+1 and 977 would return 23, being 9+7+7.

I've commented out some of my attempts before thinking of charAt(0) and some n's will have as many as 3 digits, maybe more if I don't have to limit it, but the largest test case stops at 997 I think, but an extra decimal for margin of error. I finally got something to work, but it feels like I'm going the long way to get there.. Surely there's something already built into to JavaScript I'm overlooking to reduce the value of a string. Or should I be trying to turn it into an array of digits?

function isItTHREED(n) {
  //  https://www.thoughtco.com/how-to-determine-number-is-prime-2312518

   //  Try 3.  Take the number, and add the digits up, when those digits are divisible by 3, the number is not prime.
  //          Take 2469, those digits add up to 21, and 21 is divisible by 3, therefore 2469 is not a prime number.
console.log('3s',n);
  n = n.toString();
  var digitONE = Number(n.charAt(0));
  var digitTWO = Number(n.charAt(1));
  var digitTHREE = Number(n.charAt(2));
  var digitFOUR = Number(n.charAt(3));
  console.log('digits',digitONE);
  console.log('digits',digitTWO);
  console.log('digits',digitTHREE);
  console.log('digits',digitFOUR);
  var testing = digitONE + digitTWO +digitTHREE + digitFOUR
  console.log(testing);
  //if(testing % 3 != 0)

  /*
  n = n.toString();
  n = n.split('');
  //num = num.split('');
  n = [n];
  console.log("num", n);
  */
   n = testing;
  return n;
} //end of isItTHREED

isItTHREED(10); // should return 1
isItTHREED(21); // should return 3
isItTHREED(977); // should return 23.

CodePen

\$\endgroup\$
  • \$\begingroup\$ What you are trying to do is called calculating a digit sum. \$\endgroup\$ – Ben Steffan Jul 1 '17 at 20:07
  • \$\begingroup\$ I don't actually speak JavaScript, but the general algorithm you would see implemented (in any language) goes like this: while number not 0: result = result + num % 10; num = num / 10 Where '%' is the modulo operator \$\endgroup\$ – Ben Steffan Jul 1 '17 at 20:09
  • \$\begingroup\$ Any time you find yourself creating variables like digitOne, digitTWO, etc. you should be using an array. Then you won't have an arbitrary limit on the number of digits. \$\endgroup\$ – Barmar Jul 1 '17 at 20:34
3
\$\begingroup\$

As others have mentioned, you are attempting to find the digital sum of a given number. In JavaScript, you can do the following:

function digitalSum(number) {
  return (
    number
      .toString()
      .split('')
      .map(c => parseInt(c))
      .reduce((a, b) => a + b)
  )
}

As it intuitively appears, the code above does the following:

  1. convert the number into a string
  2. split the string by the empty string, thus each digit/character of the string is an individual element of the new list
  3. converts each digit from a string to an actual number
  4. Reduces the list by the sum function

There are other ways of accomplishing this task, but I believe the above is rather easy to understand.

\$\endgroup\$
  • 1
    \$\begingroup\$ while everyone's answer has added to my understanding, your answer helps me understand it from where I'm currently at \$\endgroup\$ – TurtleWolf Jul 1 '17 at 21:53
3
\$\begingroup\$

Separation of concerns

The isItTHREED function does too many things. When designing functions, it's strongly recommended that they do one thing and do it well.

Think of the big steps needed to implement this task:

  • Extract the digits from the input string
  • Sum the digits
  • Check if the sum is divisible by 3

The first 2 steps would be good together in one function to produce the sum of digits, let's call it sumOfDigits. Separating to two functions would not be optimal in the current context, because it would require generating an array, which is just overkill.

The 3rd step could use sumOfDigits.

Calculating the sum of digits

The current implementation does roughly this:

  • convert the input to a string
  • extract the first 4 characters one by one and convert to number
  • sum the 4 digits

That's a lot of unnecessary work. And the solution is limited to input with maximum 4 digits. And while it works for input with less then 4 digits, it's a bit hacky when referencing indexes in n that might not exist.

Consider this alternative implementation without unnecessary type conversions:

function sumOfDigits(n) {
  var work = n;
  var sum = 0;
  while (work > 0) {
    sum += work % 10;
    work = Math.floor(work / 10);
  }
  return sum;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.