简体   繁体   中英

javascript challenge on CodeWars: what's wrong with my solution?

I'm fairly new to programming and javascript, and recently started working on CodeWars challenges. I wasn't able to pass the challange below with my solution, and even when I compared against solutions from other users, I couldn't find what the issue was with mine.

Challenge:

"Complete the squareSum/square_sum/SquareSum method so that it squares each number passed into it and then sums the results together.

For example: squareSum([1, 2, 2]); // should return 9"

My code:

function squareSum(numbers){
  var sqNum = numbers.map(num=>num*num);
  var addNum = sqNum.reduce((acc,curr)=> acc + curr);
  return addNum
};

Am I missing something?

function squareSum(numbers){
    return numbers.reduce((acc,curr)=> acc + curr * cur, 0);
}

Avoid the full copy with map. You will most likely hit either the run time or memory limit for the test cases with large arrays.

CodeWars is not only about correct implementation, but also about reasonable efficiency.

This solution per se is working ok, I have tried at codepen. It has to be with the way you present your answer. I don't know how exactly codewars works, but keep in mind that you are not calling the function squareSum anywhere. And when you do it, remember to pass the numbers within an array.

function squareSum(numbers){
  var sqNum = numbers.map(num=>num*num);
  var addNum = sqNum.reduce((acc,curr)=> acc + curr);
  console.log( addNum )
};

squareSum([1, 2, 2]);

This works just fine

This is my solution the code wars challenge...Was well

 function square_sum(numbers) {
    return numbers.reduce(function(sum, x) {
      return (x * x) + sum;
    }, 0)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM