The base converter algorithm

We can modify the previous algorithm to make it work as a converter from decimal to the bases between 2 and 36. Instead of dividing the decimal number by 2, we can pass the desired base as an argument to the method and use it in the division operations, as shown in the following algorithm:

function baseConverter(decNumber, base) {  const remStack = new Stack();  const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; // {6}   let number = decNumber;  let rem;  let baseString = '';  if (!(base >= 2 && base <= 36)) {    return '';  }  while (number > 0) {    rem = Math.floor(number % base);    remStack.push(rem);    number = Math.floor(number / base);  }  while (!remStack.isEmpty()) {    baseString += digits[remStack.pop()]; // {7}  } return ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.