I started learning website development (just over 2 months now), learning frontend with HTML, CSS and JS. I am currently on the Eloquent JavaScript book. I did the "sum of range" exercise in chapter 4 of the book, I was able to code the range function, got a little help on the sum function, and competed the exercise. What I want now is to know how well written my solution is, and if there is a better way. This is the exercise and my code solution follows:
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
.
Next write a sum
function that takes an array of numbers and returns the sum of these numbers.
As a bonus assignment, modify your range function to take an optional third argument that indicates the "step" value used when building the array. If no step is given, the elements go up by increments of one, corresponding to the old behaviour. The function call range(1, 10, 2)
should return [1, 3, 5, 7, 9]
. Make sure it also works with negative step values so that range(5, 2, -1)
returns [5, 4, 3, 2]
.
My solution:
function range(start, end, skip) {
let arr = [];
let count;
for (count = start;start < end ? count<=end : count >= end ; count+= skip) {
arr.push(count);
}
return arr;
}
function sum(numbers) {
result = 0;
for (let num of numbers) {
result += num;
}
return result;
}
All I need now is a somewhat "code inspection". Thanks in advance!
question from:
https://stackoverflow.com/questions/65936272/is-my-solution-to-the-sum-of-range-exercise-in-chapter4-of-eloquent-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…