Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

web deployment - Is my solution to the "Sum of Range" exercise in Chapter4 of Eloquent JavaScript okay? Or is there a way to make it better?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...