How to implement toString to convert a number to a string?

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

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

In addition to:

  • converting a number by concatenating an empty string 123+""
  • using the built-in function toString() (123).toString()
  • create a new line String(123)

How else to implement toString()in javascript?

+4
source share
4 answers

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"
Run codeHide result

You can also use the DOM attributes:

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

Or join the array

return [value].join();

And big and so on. There are many things that internally use the abstract ToString operation .

+1
source

, . , 10 . , .

EDIT: , (, , ).

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('');
};

:

>> toString(678)
"678"
0

. 10 10 , 48 String.fromCharCode , .

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));
Hide result
0

ES6, .

var a = 5;
console.log(`${a}`);
-1

Source: https://habr.com/ru/post/1655878/


All Articles