DEV Community

Cesar Del rio
Cesar Del rio

Posted on

#46 - Sum of a sequence - Codewars Kata (7 kyu)

How can you help?
You can support by buying a coffee ☕️
Follow me on Github
Follow me on Twitter

Instructions

Task:
our task is to make function, which returns the sum of a sequence of integers.

The sequence is defined by 3 non-negative values: begin, end, step (inclusive).

If begin value is greater than the end, function should returns 0

Examples

2,2,2 --> 2
2,6,2 --> 12 (2 + 4 + 6)
1,5,1 --> 15 (1 + 2 + 3 + 4 + 5)
1,5,3 --> 5 (1 + 4)


My solution:

const sequenceSum = (begin, end, step) => {
  var count = 0;
  for (let i = begin; i <= end; i += step) {
    count += i;
  }
  return count;
};
Enter fullscreen mode Exit fullscreen mode

Explanation

First I made the variable count, in which I'll save the results of the sums in the loop

var count = 0;
Enter fullscreen mode Exit fullscreen mode

Then I used a for loop, in which I started with the value of the begin param, it will iterate until the "i" value is equal to the end value, and in each iteration the "i" value will be summed the "step" param value.
And in each iteration I summed the "i" value to count

  for (let i = begin; i <= end; i += step) {
    count += i;
  }
Enter fullscreen mode Exit fullscreen mode

At the end I just returned count

return count;
Enter fullscreen mode Exit fullscreen mode

What do you think about this solution? 👇🤔

Solve this Kata 👨🏽‍💻

Top comments (0)