5

I was asked during an interview to implement toString() to convert a number into a string.

toString() n => s 123 => "123"

Aside from:

  • converting the number by concatenating an empty string 123+""
  • using the native toString() function (123).toString()
  • creating a new string String(123)

How else could toString() be implemented in javascript?

Patrick
  • 1,410
  • 2
  • 19
  • 37

4 Answers4

1

You can use it as the property name of an object.

function toString(value) {
  // Coerces value to a primitive string (or symbol)
  var obj = {};
  obj[value] = true;
  return Object.getOwnPropertyNames(obj)[0];
}
console.log(toString(123));  // 123      -> "123"
console.log(toString(1.23)); // 1.23     -> "1.23"
console.log(toString(NaN));  // NaN      -> "NaN"
console.log(Infinity);       // Infinity -> "Infinity"
console.log(toString(-0));   // -0       -> "0"
console.log(toString(1e99)); // 1e99     -> "1e+99"

You can also use DOM attributes:

var obj = document.createElement('div');
obj.setAttribute('data-toString', value);
return obj.getAttribute('data-toString');

Or join an array

return [value].join();

And a big etcetera. There are lots of things which internally use the ToString abstract operation.

Oriol
  • 274,082
  • 63
  • 437
  • 513
0

The trick here is to consider a number as a series of digits. This is not an inherent property of numbers, since the base-10 representation that we use is quite arbitrary. But once a number is represented as a series of digits, it is quite easy to convert each digit individually to a string, and concatenate all such strings.

EDIT: As pointed out, this only takes integers into consideration (which is probably acceptable for an interview question).

var intToDigits = function(n) {
    var highestPow = 1;
    while (highestPow < n) highestPow *= 10;
    var div = highestPow / 10;

    // div is now the largest multiple of 10 smaller than n

    var digits = [];

    do {
        var digit = Math.floor(n / div);
        n = n - (digit * div);
        div /= 10;
        digits.push(digit);
    } while (n > 0);

    return digits;
};

var toString = function(n) {
    var digitArr = intToDigits(n);
    return digitArr.map(function(n) {
        return "0123456789"[n];
    }).join('');
};

Usage:

>> toString(678)
"678"
Gershom Maes
  • 7,358
  • 2
  • 35
  • 55
0

This works for integers. It takes the number modulo 10 and divides it by 10 repeatedly, then adds 48 to the digits and uses String.fromCharCode to get a string value of the digits, then joins everything.

function toString(n){
  var minus = (n < 0
      ? "-"
      : ""),
    result = [];
  n = Math.abs(n);
  while(n > 0){
    result.unshift(n % 10);
    n = Math.floor(n / 10);
  }
  return minus + (result.map(function(d){
    return String.fromCharCode(d + 48);
  })
    .join("") || "0");
}

console.log(toString(123123));
console.log(toString(999));
console.log(toString(0));
console.log(toString(-1));
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
-1

If you're using ES6 you could use template literals.

var a = 5;
console.log(`${a}`);
Oussama BEN MAHMOUD
  • 1,442
  • 12
  • 19