Everyone Can Code!

JavaScript Kata #13: Grasshopper - Summation

By YayoDrayber | Learn To Code With Me | 16 Aug 2022


If you missed the introductory post, it's here. For a list of previously solved katas, please refer to the bottom of this page.

If this is your first time seeing my post, please note - these katas are probably randomly assigned per user so please don't go into Codewars thinking we will have exactly the same user experience, I am just posting these in the order that I got them.

Kata #13

DESCRIPTION:

Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

For example:

summation(2) -> 3
1 + 2

summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8

Starting code:

var summation = function (num) {
  // Code here
}

My attempt that worked:

function summation(num) {
  let sum = 0
  for (i = num; i >= 1 ; i--){
    sum += i
  }
  return sum
}

Rank #1 'Best Practice' with 857 votes and 97 'Clever' votes at the time of writing:

var summation = function (num) {
  let result = 0;
  for (var i = 1; i <= num; i++) {
    result += i;
  }
  
  return result;
}

Only difference with my approach is that this one counted up to the 'num' variable whereas I counted down from it. 

Rank #2 one-liner with 355 votes and 1445 'Clever' votes at the time of writing:

const summation = n => n * (n + 1) / 2;

Ranks #3 and #7 also used the same formula, probably math geniuses. Who'd have thunk it'd be this simple, right? 🤪

Surprisingly, three people (users asma gharbimimiweary and user4019457) who used the .reduce method only clocked in at rank #8:

const summation = num => (
  Array(num).fill(true)
    .reduce((sum, item, index) => sum + index + 1, 0)
);

That's it for Kata #13, stay tuned for more katas to be solved!

Link to Kata #1: Square(n) Sum

Link to Kata #2: Convert a Number to a String

Link to Kata #3: DNA to RNA Conversion

Link to Kata #4: Remove First and Last Character

Link to Kata #5: MakeUpperCase

Link to Kata #6: Total amount of points

Link to Kata #7: A Needle in the Haystack

Link to Kata #8: Sum of positive

Link to Kata #9: Basic Mathematical Operations

Link to Kata #10: Beginner - Reduce but Grow

Link to Kata #11: Square Every Digit

Link to Kata #12: Friend or Foe?

How do you rate this article?

2


YayoDrayber
YayoDrayber

A Yayo, A Drayber, among others.


Learn To Code With Me
Learn To Code With Me

Just started with Codewars and will be posting the solutions I came up with here and the apparent best practices.

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.