I am trying to use array.reduce on an array representing a single binary value. For instance [1,0,1] in binary would convert to 5 in decimal.
I have been able to succesfully convert between binary and decimal using a while loop, but would like to upgrade my code to use the reduce method.
What I have implemented so far is accurate up to 6 elements in the array. I am not sure why, but after 6 digts, the conversion fails.
In addition, I am using a formula to make the conversion. For example: to convert 111001 to decimal, you would have to do (1*2^5) + (1*2^4) (1*2^3) + (0*2^2) + (0*2^1) + (1*2^0).
const getDecimalValue = function (head) {
let total = head.reduce(
(sum) =>
sum + (head.shift() * Math.pow(2, head.length))
)
return total
}
console.log(getDecimalValue([1, 0, 1]) == 5)
console.log(getDecimalValue([1, 1, 1, 0, 0, 1]) == 57)
console.log(getDecimalValue([1, 1, 1, 0, 0, 1, 1]) == 115)
console.log(getDecimalValue([0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0]) == 7392)
console.log(getDecimalValue([1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0]) == 18880)
This was my code using the while loop
let sum = 0
while ((i = head.shift()) !== undefined) {
sum += (i * Math.pow(2, head.length))
console.log(i * Math.pow(2, head.length))
}
return sum