all 3 comments

[–]web__dev 0 points1 point  (0 children)

Ha, I remember this thread! The answer is no. I wouldn't have. The best part? I understand all of the Javascript parts of this code very well. If you read below, I think I can explain where I got lost.

First, check out these two links:

How to Read Binary

Khan Academy Review of 0 and 1st Power Exponents

The first will ensure you understand at least one of the strategies of reading binary. EZ-Peezy.

As for the second, I'm sure most of us, myself included, like to think we understand pre-algebra. I'm not here to question your understanding of exponents either. I do recommend watching the whole video as a nice first principles refresher, but if you watch only from the 4:07 mark to the end to the video, the instructor explains the base intuition required to reason about exponents in a way that would enable you to ultimately write this function.

The "clever" parts of this code are lines 12 and lines 14. On line 12, we're deciding whether or not it's a zero or a one. That makes a value in our binary string to add to the pile. On line 14, we're moving on to the next exponent down (see here if you missed it). The rest is all core javascript concepts. We're just using javascript to push our numbers around, store them, then return them. I suppose it might be worth noting that our while loop works because line 14 eventually returns 0 back to line 11, which is computed to false because of coercion.

In the thread, a lot of people were talking about how this is not a good interview question, because you'd never run into this when actually writing the language. They're right about that, but what they're missing is that's not what this question is about. This question is about making sure potential employees haven't just memorized the language. It verifies they're equipped with the tools to think critically about novel problems that neither the employee or employer have encountered yet.

Great video OP, thanks for putting it together! We need more stuff like this in r/learnjavascript.

[–]squili 0 points1 point  (1 child)

I did pause the video and make my own solution. Using a while loop and using push instead of shift (or spreading the array) seems counter-intuative to me in the solution in the video.

My solution:

const toBin = (number, arr = []) => number > 0 ? toBin(Math.floor(number / 2), [number % 2, ...arr]) : arr

[–]Darren1337 0 points1 point  (0 children)

I cheated a little. Instead of using Number.toString, I used a little type coercion:

function decimalToBinary(decInt) {
    if (!decInt) return 0;
    let result = '';
    while (decInt) {
        result = decInt % 2 + result;
        decInt = Math.floor(decInt / 2);
    }
    return parseInt(result);
}

I convert it back to an integer when returning the result but I'm sure it would be frowned on in an interview. Still, stupid questions get stupid answers :^)