mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 17:50:39 +08:00
24 lines
623 B
JavaScript
24 lines
623 B
JavaScript
function hexToInt (hexNum) {
|
|
const numArr = hexNum.split('') // converts number to array
|
|
return numArr.map((item, index) => {
|
|
switch (item) {
|
|
case 'A': return 10
|
|
case 'B': return 11
|
|
case 'C': return 12
|
|
case 'D': return 13
|
|
case 'E': return 14
|
|
case 'F': return 15
|
|
default: return parseInt(item)
|
|
}
|
|
})
|
|
}
|
|
|
|
function hexToDecimal (hexNum) {
|
|
const intItemsArr = hexToInt(hexNum)
|
|
return intItemsArr.reduce((accumulator, current, index) => {
|
|
return accumulator + (current * Math.pow(16, (intItemsArr.length - (1 + index))))
|
|
}, 0)
|
|
}
|
|
|
|
export { hexToInt, hexToDecimal }
|