Skip to content

Commit 4c625f0

Browse files
feat: add hexadecimal to decimal conversion
1 parent 5c39e87 commit 4c625f0

2 files changed

Lines changed: 76 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @function hexadecimalToDecimal
3+
* @description Converts a hexadecimal number (base-16) string to its decimal
4+
* (base-10) equivalent without using JavaScript's built-in parseInt.
5+
* @param {string} hex - A string representing a hexadecimal number
6+
* @returns {number} - The decimal equivalent of the hexadecimal number
7+
* @see https://en.wikipedia.org/wiki/Hexadecimal
8+
* @example hexadecimalToDecimal("FF") => 255
9+
* @example hexadecimalToDecimal("10") => 16
10+
* @example hexadecimalToDecimal("0") => 0
11+
*/
12+
const hexadecimalToDecimal = (hex) => {
13+
if (typeof hex !== 'string' || !/^[0-9a-fA-F]+$/.test(hex)) {
14+
throw new TypeError(
15+
'Input must be a valid hexadecimal string containing only 0-9 and A-F'
16+
)
17+
}
18+
return hex
19+
.toUpperCase()
20+
.split('')
21+
.reverse()
22+
.reduce((acc, char, index) => {
23+
const value =
24+
char >= 'A' ? char.charCodeAt(0) - 55 : char.charCodeAt(0) - 48
25+
return acc + value * Math.pow(16, index)
26+
}, 0)
27+
}
28+
29+
export { hexadecimalToDecimal }
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { hexadecimalToDecimal } from '../HexadecimalToDecimal.js'
2+
3+
describe('hexadecimalToDecimal', () => {
4+
test("hexadecimalToDecimal('0') returns 0", () => {
5+
expect(hexadecimalToDecimal('0')).toBe(0)
6+
})
7+
8+
test("hexadecimalToDecimal('A') returns 10", () => {
9+
expect(hexadecimalToDecimal('A')).toBe(10)
10+
})
11+
12+
test("hexadecimalToDecimal('F') returns 15", () => {
13+
expect(hexadecimalToDecimal('F')).toBe(15)
14+
})
15+
16+
test("hexadecimalToDecimal('10') returns 16", () => {
17+
expect(hexadecimalToDecimal('10')).toBe(16)
18+
})
19+
20+
test("hexadecimalToDecimal('FF') returns 255", () => {
21+
expect(hexadecimalToDecimal('FF')).toBe(255)
22+
})
23+
24+
test("hexadecimalToDecimal('100') returns 256", () => {
25+
expect(hexadecimalToDecimal('100')).toBe(256)
26+
})
27+
28+
test("hexadecimalToDecimal lowercase 'ff' returns 255", () => {
29+
expect(hexadecimalToDecimal('ff')).toBe(255)
30+
})
31+
32+
test("hexadecimalToDecimal('1000') returns 4096", () => {
33+
expect(hexadecimalToDecimal('1000')).toBe(4096)
34+
})
35+
36+
test('throws TypeError for invalid hex string', () => {
37+
expect(() => hexadecimalToDecimal('GHI')).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for empty string', () => {
41+
expect(() => hexadecimalToDecimal('')).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for non-string input', () => {
45+
expect(() => hexadecimalToDecimal(255)).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)