JavaScript Kata: Sum Of All Numbers Between Two Supplied Arguments.

Return Sum Of All Integers Between The Two Unordered Supplied Args

BY indefiniteloop

A Kata on a writing JavaScript function that returns the sum of all numbers between two integers supplied, including them. If both numbers happen to be equal, the function then returns one of the two integers instead.

Problem Statement: Write a function that takes two unordered integers as arguments, and then returns the summation of all the numbers between those two integers (including them). If the two integers are the same, then the function returns one of them.

A really simple JavaScript kata to learn logic, and play around more in JavaScript. It does help if you know how to use the Math class (see below at the precise and/or elegant solution sections to know more).

Test Cases & Kata. JavaScript Kata: Sum Of All Numbers Between Two Supplied Arguments.

View Kata & Test Cases

Here’s how I solved it

function GetSum( a,b )
{
if(a==b) return a;
var sum = 0;
for(i=((a<b)?a:b);i<=((a<b)?b:a);i++)sum+=i;
return sum;
}

Precise And/Or Elegant Solution(s)

This one’s by ryanwaits (and other people). ​

const GetSum = (a, b) => {
let min = Math.min(a, b), max = Math.max(a, b);
return (max - min + 1) * (min + max) / 2;
}

Here’s another interesting solution by mufmuf

function GetSum( a,b )
{
if (a == b) return a;
else if (a < b) return a + GetSum(a+1, b);
else return a + GetSum(a-1,b);
}

Beginner’s Series

This is a great kata for learning how to implement logic. If you see the solutions above, you know what I am talking about. It’s great way to learn!

——> Sign yourself up here!

I really do hate spam as much as you. Your email will never be shared with anyone, or any party. That's a pinky promise!

• Higher Order Functions In JavaScript

Apr 7, 2016 in Code
• Generating A Tribonacci Series

Apr 14, 2016 in Code
• Sorting, Using Arrow Function(s).

Mar 31, 2016 in Code 