Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Conversions/HexadecimalToDecimal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* @function hexadecimalToDecimal
* @description Converts a hexadecimal number (base-16) string to its decimal
* (base-10) equivalent without using JavaScript's built-in parseInt.
* @param {string} hex - A string representing a hexadecimal number
* @returns {number} - The decimal equivalent of the hexadecimal number
* @see https://en.wikipedia.org/wiki/Hexadecimal
* @example hexadecimalToDecimal("FF") => 255
* @example hexadecimalToDecimal("10") => 16
* @example hexadecimalToDecimal("0") => 0
*/
const hexadecimalToDecimal = (hex) => {
if (typeof hex !== 'string' || !/^[0-9a-fA-F]+$/.test(hex)) {
throw new TypeError(
'Input must be a valid hexadecimal string containing only 0-9 and A-F'
)
}
return hex
.toUpperCase()
.split('')
.reverse()
.reduce((acc, char, index) => {
const value =
char >= 'A' ? char.charCodeAt(0) - 55 : char.charCodeAt(0) - 48
return acc + value * Math.pow(16, index)
}, 0)
}

export { hexadecimalToDecimal }
47 changes: 47 additions & 0 deletions Conversions/test/HexadecimalToDecimal.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { hexadecimalToDecimal } from '../HexadecimalToDecimal.js'

describe('hexadecimalToDecimal', () => {
test("hexadecimalToDecimal('0') returns 0", () => {
expect(hexadecimalToDecimal('0')).toBe(0)
})

test("hexadecimalToDecimal('A') returns 10", () => {
expect(hexadecimalToDecimal('A')).toBe(10)
})

test("hexadecimalToDecimal('F') returns 15", () => {
expect(hexadecimalToDecimal('F')).toBe(15)
})

test("hexadecimalToDecimal('10') returns 16", () => {
expect(hexadecimalToDecimal('10')).toBe(16)
})

test("hexadecimalToDecimal('FF') returns 255", () => {
expect(hexadecimalToDecimal('FF')).toBe(255)
})

test("hexadecimalToDecimal('100') returns 256", () => {
expect(hexadecimalToDecimal('100')).toBe(256)
})

test("hexadecimalToDecimal lowercase 'ff' returns 255", () => {
expect(hexadecimalToDecimal('ff')).toBe(255)
})

test("hexadecimalToDecimal('1000') returns 4096", () => {
expect(hexadecimalToDecimal('1000')).toBe(4096)
})

test('throws TypeError for invalid hex string', () => {
expect(() => hexadecimalToDecimal('GHI')).toThrow(TypeError)
})

test('throws TypeError for empty string', () => {
expect(() => hexadecimalToDecimal('')).toThrow(TypeError)
})

test('throws TypeError for non-string input', () => {
expect(() => hexadecimalToDecimal(255)).toThrow(TypeError)
})
})
Loading