[JS practice] Square Sum (平方求和)

Title :
Square Sum (对数组中每个元素求平方,然后求和)

Description :
Complete the squareSum method so that it squares each number passed into it and then sums the results together.

要求对输入数组里所有数字先求平方,然后再对得出的结果求和。
虽然不难,但是会考察到javascript里两个基本函数和/或一个基本对象的使用。

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

My Solution :

function squareSum(numbers){
  var sum = 0;
  numbers.forEach(function(n){
    sum = Math.pow(n, 2); // n power 2 == n * n
  });
  return sum;
}

Other Solution :

function squareSum(numbers){
  return numbers.map(square).reduce(sum);
}

function square(number) {
  return number * number;
}

function sum(firstNumber, secondNumber) {
  return firstNumber + secondNumber;
}

Ref. from codewars

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s