Last active
February 18, 2019 12:46
-
-
Save ryasmi/4953830 to your computer and use it in GitHub Desktop.
The function triangular returns the triangular number of the inputted value. For example triangular(3) would return 6 because 1 + 2 + 3 is equal to 6. This function accounts for both negative values and zero.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var triangular = function (value) { | |
var abs = Math.abs(value); | |
return ((abs / 2) * (abs + 1)) * (abs / value) || 0; | |
}; | |
// Testing code. | |
var testTriangular = function () { | |
var testTriangularValue = function (arg, value, id) { | |
console.log(triangular(arg) === value ? "Test " + id + " passed." : "Test " + id + " failed."); | |
}; | |
testTriangularValue(3, 6, 1); | |
testTriangularValue(-3, -6, 2); | |
testTriangularValue(0, 0, 3); | |
testTriangularValue(4, 10, 4); | |
testTriangularValue("hello", 0, 5); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment