This should not be problem at all but for the life of me I’m not able to put my finger on the heart of it.
I have a factory that spins out functions to determine the number of digits an integer will have. The factory is supplied a base, which is then scoped to the returned closure. The closure in turn accepts any integer and returns a digit count, mathematically.
Below are three different versions, floor, ceil and parseInt, followed by their output. Can anybody explain what is wrong with my logic? It’s Thanksgiving and I think all the food has clouded my brain. Thanks in advance for your advice.
/*
function factory(base) {
let log = Math.log;
let floor = Math.floor;
return x => { return floor(log(x) / log(base)) + 1;};
}
*/
/* floor
999 3
1000 3 // X
1001 4
255 8
256 9
4095 3
4096 4
*/
/*
function factory(base) {
let log = Math.log;
let ceil = Math.ceil;
return x => { return ceil(log(x) / log(base));};
}
*/
/* ceil
999 3
1000 3 // X
1001 4
255 8
256 8 // X
257 9
4095 3
4096 3 // X
4097 4
*/
function factory(base) {
let log = Math.log;
return x => { return parseInt(log(x) / log(base), 10) + 1;};
}
/* int
999 3
1000 3 // X
1001 4
255 8
256 9
257 9
4095 3
4096 4
4097 4
*/
// tests
decDigCount = factory(10);
console.log(999, decDigCount(999));
console.log(1000, decDigCount(1000));
console.log(1001, decDigCount(1001));
binDigCount = factory(2);
console.log(255, binDigCount(255));
console.log(256, binDigCount(256));
console.log(257, binDigCount(257));
hexDigCount = factory(16);
console.log(4095, hexDigCount(4095));
console.log(4096, hexDigCount(4096));
console.log(4097, hexDigCount(4097));
Sandbox: https://repl.it/DsBi