lundi 16 novembre 2020

Defining functions w/ for loop & if statement to return array & sum

I'm reading Eloquent JavaScipt 3rd edition to study JavaScript. I did one of the exercises in the book, and am sure it is correct. But obviously I am wrong because it gives me the different result than the solution in the book.

The goal is to

  1. write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.

  2. write a sum function that takes an array of numbers and returns the sum of these numbers

Here's my code.

function range(a, b, c = a < b ? 1 : -1){
  let numbers = [];
  
  if (c > 0) {
    for (let i = a; i <= b; i += c) numbers.push(i);
  } else {
    for (let i = a; i >= a; i += c) numbers.push(i);
  }
  return numbers;
}

function sum(array){
  let result = 0;
  for (let i = 0; i <= array.length; i++){
    result += array[i];
  }
  return result;
}

Below is the solution from book

function range(start, end, step = start < end ? 1 : -1) {
  let array = [];

  if (step > 0) {
    for (let i = start; i <= end; i += step) array.push(i);
  } else {
    for (let i = start; i >= end; i += step) array.push(i);
  }
  return array;
}

function sum(array) {
  let total = 0;
  for (let value of array) {
    total += value;
  }
  return total;
}

So, if we run

console.log(range(1, 10));
console.log(range(5, 2, -1));
console.log(sum(range(1, 10)));

my result is

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[5]
NaN

The expected result is

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[5, 4, 3, 2]
55

To me, the codes look the same. What am I missing here?

Aucun commentaire:

Enregistrer un commentaire