Recreate Number.toString(nn) in pure javascript

I’m trying convert a number into string using nn base. Basically, trying re-create Number.toString(nn)

Here is the code I have so far which produces incorrect result:

const baseData = "0123456789abcdef";
for(let i = 0; i < 257; i += 8)
{
  console.log(i, "expected:", i.toString(16), "| actual:", toBase(i, 16));
}

function toBase(n, radix)
{
  let result = "";
  const count = ~~(n / radix);
  for(let i = 0; i < count; i++)
  {
    result += baseData[~~(i % radix)];
  }
  result += baseData[~~(n % radix)];
  return result;
}
.as-console-wrapper{top:0;max-height:unset!important;overflow:auto!important;}

There must be some kind of formula for this…

Any suggestions?