Square(n) Sum

Complete the square sum function so that it squares each number passed into it and then sums the results together.

For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9.

Input

We’re given an array. This means our answer will likely be found using JavaScript’s array methods, so don’t re-invent the wheel.

Output

A singe value that represents the sum of all the squared values.

Split the problem into smaller parts

Square each value in the array.

First we determine how to Square a value in JavaScript.

Math.pow(value, exponent)

Next we consider how we could do this to each value in the array. We could use a foreach loop and iterate through the array. Or we could use Array.prototype.map(), which will iterate through the array and return a new array. Let’s use map().

function squareSum(numbers){
  
  const squaredNumbers = numbers.map((element) => {
    //square each element
    return Math.pow(element,2)
  }) 
  console.log(`new array is ${squaredNumbers}`)

}

Sum the squared values

Now that we have an array of squared numbers we can sum all the numbers in this new array to get our desired output. We’ll use another JavaScript array method called Array.prototype.reduce(). Reduce iterates over an array just like map does, but returns a single value instead of a new array. It does this by keeping track of the “previous value” and the “current value.” The previous value is the result of the last call, and the current value is the element of this iteration.

function squareSum(numbers){
  
  const squaredNumbers = numbers.map((element) => {
    //square each element
    return Math.pow(element,2)
  })
  
  const squaredSum = squaredNumbers.reduce((previousValue, currentValue) => {
    //Add the running total to the current element
    return previousValue + currentValue
  })
  console.log(`squared sum value is ${squaredSum}`)

  return squaredSum

}

Unit testing and completion

The above code fails the tests on Codewars when the original array is blank. While it would have been nice to have this as a requirement in the description, it makes sense that an empty array might return 0 instead of causing an error. So let’s check for that before our previous code and return 0 if the array is empty. We’re going to use the Array.prototype.length property.

If the array is empty, the length property will be 0. Since 0 counts as false in a conditional, we’re going to negate the length property. What this means is that when the length is 0, our if-statement will resolve true and we will exit the function with a return value of 0 to satisfy the test.

function squareSum(numbers){

  //Return 0 if array is empty
  if(!numbers.length) return 0

  const squaredNumbers = numbers.map((element) => {
    //square each element
    return Math.pow(element,2)
  })
  
  const squaredSum = squaredNumbers.reduce((previousValue, currentValue) => {
    //Add the running total to the current element
    return previousValue + currentValue
  })
  console.log(`squared sum value is ${squaredSum}`)

  return squaredSum

}

Refactoring

This code is readable but verbose. We can shrink this down by combining the two steps, removing the variables, and using a ternary operator instead of an if statement. Here is an example of short but equivalent code.

function squareSum(numbers){
  return (numbers.length ? numbers.map((e)=>Math.pow(e,2)).reduce((p,c)=>p+c) : 0)
}

Leave a Reply