Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Last active February 18, 2019 12:46
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryasmi/4953830 to your computer and use it in GitHub Desktop.
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.
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