Programing challenge: digits of base n

By Xah Lee. Date: .

ok. a coding challenge. write a function f(n, b) return a list of digits. e.g.

WolframLang IntegerDigits 2022-08-26
WolframLang IntegerDigits 2022-08-26

JavaScript, python, elisp, golang i can check. no lib. must return a list of int.

solutions

const f = ((n, b) => {
  if (b === 1) return "b cannot be 1";
  const xdigits = [];
  let nn = n, bb = b;

  xdigits.unshift(nn % bb);
  nn = Math.floor(nn / bb);

  while (nn > 0) {
    xdigits.unshift(nn % bb);
    nn = Math.floor(nn / bb);
  }
  return xdigits;
});

console.log(f(31, 16)); // [ 1, 15 ]
console.log(f(31, 2)); // [ 1, 1, 1, 1, 1 ]
console.log(f(31, 4)); // [ 1, 3, 3 ]
console.log(f(9043977, 89)); // [ 12, 73, 68, 64 ]
// 2022-08-27 by triangle
function f_triangle(n, b) {
  if (b === 1) return "b cannot be 1";
  let digits = [];
  while (n >= b) {
    digits.unshift(n % b);
    n = Math.floor(n / b);
  }
  digits.unshift(n);
  return digits;
}

console.log(f_triangle(9043977, 89)); // [ 12, 73, 68, 64 ]
// 2022-08-27 by georrg
const f_georrg = (a, b) => a >= b ? [...f_georrg(Math.floor(a / b), b), a % b] : [a];

console.log(f_georrg(9043977, 89)); // [ 12, 73, 68, 64 ]

benchmark

// file name: bench228.js

// 2022-08-27 compare speed

const f1 = ((n, b) => {
  if (b === 1) return "b cannot be 1";
  const xdigits = [];
  let nn = n, bb = b;

  xdigits.unshift(nn % bb);
  nn = Math.floor(nn / bb);

  while (nn > 0) {
    xdigits.unshift(nn % bb);
    nn = Math.floor(nn / bb);
  }
  return xdigits;
});

const f2 = (a, b) => a >= b ? [...f2(Math.floor(a / b), b), a % b] : [a];

Deno.bench("f1", () => { f1(9043977025421253**4, 2); });
Deno.bench("f2", () => { f2(9043977025421253**4, 2); });

// benchmark      time (avg)             (min … max)       p75       p99      p995
// ------------------------------------------------- -----------------------------
// f1           18.5 µs/iter    (17.3 µs … 140.7 µs)   18.5 µs   21.9 µs     58 µs
// f2          49.41 µs/iter    (37.2 µs … 414.5 µs)   39.2 µs  114.2 µs  120.9 µs