I am doing the “All Your Base” JavaScript exercise. My toBaseTen
method. works perfectly. But, my toBaseX
is a bit broken. Well, kind of a lot. So, first of all, my while loop was never breaking, so I posted on a reddit, and they told me to use a forced-breaking loop. I replaced true
with BREAKER--
. The loop eventually breaks after 10,000 iterations if BREAKER
is never equal to zero.
When I ran the tests for my code below, 7 tests passed! But then, I received an error for Test 6: Converter > trinary to hexadecimal. You can go to this track yourself to see the context and run it, not gonna provide every single detail. Here is the error I got:
Error: expect(received).toEqual(expected) // deep equality
- Expected - 1
+ Received + 2
Array [
2,
- 10,
+ 1,
+ 0,
]
I am not good at diffs, but I think that means that the output [2, 10]
is expected but [2, 1, 0]
was received.
I have no idea how to fix this. Can y’all help me out please? I am so stuck, tried so many things, and my code isn’t working. I hope you guys know what’s going on.
//
// This is only a SKELETON file for the 'All Your Base' exercise. It's been provided as a
// convenience to get you started writing code faster.
//
const toBaseTen = (number, from) => {
let memory = 0;
for (let i = 0; i < number.length; i++) {
let num = number[i];
let base = (number.length - 1) - i;
let final = num * (from ** base);
memory += final;
}
return memory;
}
const toBaseX = (number, to) => {
let BREAKER = 10000;
let buffer = number;
let memory = [];
while (BREAKER--) {
let quotient = Math.floor(buffer/to);
let remainder = buffer % to;
buffer = quotient;
memory.unshift(remainder);
if (quotient == 0) {break}
}
return parseInt(memory.join(''));
}
export const convert = (number, from, to) => {
let decimal = toBaseTen(number, from);
let integer = toBaseX(decimal, to);
return String(integer).split('').map(Number);
};