Lansana - 7 months ago 37

Javascript Question

I am trying to create a function that takes in 8-bit binary and gives you the sum.

I'm having trouble doing

`num + num`

In my reduce function, I create a sum and add together the value of the number translated in binary:

`const enumerableBinaryMap = {`

0: 128,

1: 64,

2: 32,

3: 16,

4: 8,

5: 4,

6: 2,

7: 1

};

function sum (arr) {

return arr.reduce((sum, val, index) => {

return sum + val === 1 ? enumerableBinaryMap[index] : 0;

}, 0);

}

sum([0, 0, 0, 1, 0, 0, 0, 1]); // 1, should be 17

The problem occurs when I get to the first 1 in the array of binary numbers.

For instance, take a look below at the values on each call of the reducer:

- sum = 0, val = 0, index = 0
- sum = 0, val = 0, index = 1
- sum = 0, val = 0, index = 2
- sum = 0, val = 1, index = 3
- sum = 16, val = 0, index = 4
- sum = 0, val = 0, index = 5 <--- BOOM!

As you can see above, the return value of the 5th call in the reducer is the culprit here. Why does sum equal 0 on the 6th call? It should still be 16 because we returned 16 + 0?

And I can verify my implementation of reduce works, because the following below works, and it's essentially the same thing I'm doing:

`[1, 2, 3, 4, 5].reduce((sum, val) => sum + val, 0); /// 15`

Anyone know what's going on?

Answer

Is a problem of operator precedence. The code you've shown is interpreted as

```
return (((sum + val) === 1) ? enumerableBinaryMap[index] : 0);
```

whereas you want

```
return (sum + ((val === 1) ? enumerableBinaryMap[index] : 0));
// ^ ^
```

Add a couple of parenthesis to fix it or use

```
return val === 1 ? sum + enumerableBinaryMap[index] : sum;
```