-1

I'm working on some practice problems using higher- order functions and while I was able to solve this problem. I can't help but think this code is ugly and not the most eloquent it could be. Is there a way to combined map and reduce is a cleaner way than I have done ? Additionally, is there any other methods or improvements I could have used here ? I'm just looking to get better and any feedback would be appreciated.

Problem: Given a number, "sumDigits" returns the sum of all its digits.If the number is negative, the first digit should count as negative.

function sumDigits(num) {

  //create array of number char
  var string = num.toString().split('');

  //if first char is negative symbol let the first numeric element be negative
  if (string[0] === "-") {
    string[1] = '-' + string[1];
    string.shift();
  }

  //convert string to int
  var toInteger = string.map(function(x) {
    return Number(x);
  });

  //get sum 
  return toInteger.reduce(function(sum, current) {
    sum += current;
    return sum;
  })
}

sumDigits(-316);
kukkuz
  • 41,512
  • 6
  • 59
  • 95
ayeteo
  • 244
  • 3
  • 5
  • 14

1 Answers1

0

You don't need to use map at all, if you convert to number inside the reduce. Here I used the unary + operator to convert the string to a number instead of the Number constructor, but that is not better than the Number constructor, just a habit:

function sumDigits ( num ) {
    const chars = num.toString( ).split( '' );

    // Subtract first digit if the string starts with a '-'
    // Needs to be subtracted twice, since it is included in the sum
    return ( chars[0] === '-' ? -2*chars[1] : +chars[0] ) +
      chars.slice( 1 ).reduce( (sum, value) => sum + +value, 0 )
    ;
}
Paul
  • 139,544
  • 27
  • 275
  • 264