💾valueToString()

convert a value to string.

JSvaluetypeconversion ⟩ valueToString()

convert a value to its most "natural" string representation.

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)]
--------------------------------------------------

Last updated