๐พvalueToString()
convert a value to string.
JS โฉ value โฉ type โฉ conversion โฉ valueToString()
convert a value to its most "natural" string representation.
replit๏ผ valueToString(), require๏ผisObject()
const { isObject } = require('./isObject.js');
// โญ๏ธ valueToString(value)
function valueToString(value){
const str = String(value);
// ------------ primitive ------------
if (!isObject(value)) {
if (typeof value === 'string') return `'${str}'`;
return str;
}
// ------------ object ------------
// array
if (Array.isArray(value)) return '['
+ value.map(x => valueToString(x)).join(',')
+ ']';
// Set
if (str === '[object Set]')
return `{${[...value].map(x => valueToString(x)).join(', ')}}`;
// Map
if (str === '[object Map]')
return `{${[...value].map(p => `${p[0]}โ${valueToString(p[1])}`).join(', ')}}`;
// function: return its code
if (typeof value === 'function') return value.toString();
// other object, try to get its methods as well.
let result = [];
for (let key in value) {
result.push(`${key}: ${valueToString(value[key])}`);
}
return `{${result.join(', ')}}`;
}
// export
module.exports = { valueToString };
๐็ฏไพ๏ผ
string value
--------------------------------------------------
'' ''
'yes' 'yes'
'0' '0'
'3' '3'
'+5' '+5'
'-4.3' '-4.3'
--------------------------------------------------
true true
false false
--------------------------------------------------
0 0
5.6 5.6
-7.8 -7.8
NaN NaN
--------------------------------------------------
null null
undefined undefined
--------------------------------------------------
[] []
[0] [ 0 ]
[4.6] [ 4.6 ]
[2,3] [ 2, 3 ]
[1,2,3,4] [ [ 1, 2 ], [ 3, 4 ] ]
--------------------------------------------------
{1, 'hi'} Set(2) { 1, 'hi' }
--------------------------------------------------
{xโ0} Map(1) { 'x' => 0 }
--------------------------------------------------
{} {}
{a: 2} { a: 2 }
{a: 2, f: () => 1} { a: 2, f: [Function: f] }
--------------------------------------------------
() => true [Function (anonymous)]
() => 1 [Function (anonymous)]
--------------------------------------------------
codepen โฉ object.toString() ?
codesandbox โฉ compare: ~~, +, !!, Math.trunc
helper functions (0.1.8)
Last updated