Skip to content

Commit d6be3a4

Browse files
algorithm: Hexagonal number (TheAlgorithms#1265)
1 parent 71d3d44 commit d6be3a4

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Maths/HexagonalNumber.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/*
2+
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
3+
* Hexagonal Number: https://en.wikipedia.org/wiki/Hexagonal_number
4+
* The nth hexagonal number hn is the number of distinct dots in a pattern of dots
5+
* consisting of the outlines of regular hexagons with sides up to n dots, when the
6+
* hexagons are overlaid so that they share one vertex.
7+
*/
8+
9+
/**
10+
* @function hexagonalNumber
11+
* @description -> returns nth hexagonal number
12+
* @param {Integer} number
13+
* @returns {Integer} nth hexagonal number
14+
*/
15+
16+
export const hexagonalNumber = (number) => {
17+
if (number <= 0) {
18+
throw new Error('Number must be greater than zero.')
19+
}
20+
return number * (2 * number - 1)
21+
}

Maths/test/HexagonalNumber.test.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { hexagonalNumber } from '../HexagonalNumber'
2+
3+
const expectedValuesArray = [1, 6, 15, 28, 45, 66, 91, 120, 153, 190, 231, 276, 325, 378, 435, 496, 561, 630, 703, 780, 861, 946]
4+
5+
describe('Testing hexagonalNumber', () => {
6+
for (let i = 1; i <= 22; i++) {
7+
it('Testing for number = ' + i + ', should return ' + expectedValuesArray[i], () => {
8+
expect(hexagonalNumber(i)).toBe(expectedValuesArray[i - 1])
9+
})
10+
}
11+
12+
it('should throw error when supplied negative numbers', () => {
13+
expect(() => { hexagonalNumber(-1) }).toThrow(Error)
14+
})
15+
16+
it('should throw error when supplied zero', () => {
17+
expect(() => { hexagonalNumber(0) }).toThrow(Error)
18+
})
19+
})

0 commit comments

Comments
 (0)