xpl / as-table

A simple function that prints objects as ASCII tables. Supports ANSI styling and weird Unicode 💩 emojis – they won't break the layout.
http://npmjs.com/package/as-table
MIT License
62 stars 10 forks source link

additional argument to print #7

Closed neolao closed 5 years ago

neolao commented 5 years ago

Add a format function to customize cell output for objects.

xpl commented 5 years ago

@neolao Thanks for the PR! It is indeed a very useful feature.

But there may be a bit of confusion with the existing print function... What do you think — is it possible to avoid introducing the new format function, but just extend the semantics of the existing print? It would require lifting the application of print from asColumns:

        cells           = rows.map (r => r.map (c => (c === undefined) ? '' : cfg_.print (c).replace (/\n/g, '\\n'))),

...to asTable (the "front end" of asColumns) — to somewhere here:

/*  Print arrays  */

    if (arr[0] && Array.isArray (arr[0]))
        return asColumns (arr, cfg).join ('\n') // <---- here?

Just as you apply the newly introduced format below that block, here:

/*  Print objects   */

    const colNames        = [...new Set ([].concat (...arr.map (O.keys)))],
          columns         = [colNames.map (cfg.title), ...arr.map (o => colNames.map (key => o[key]))],

So that asColumns would receive the array that is already formatted with the print. For objects the second argument of print would be the key (so basically what the format does), and for arrays it would be the column index.

What do you think?

neolao commented 5 years ago

Oh yes, good point. I will make a change

neolao commented 5 years ago

Done with 2 use cases for the tests

xpl commented 5 years ago

@neolao That is really awesome, thanks. I'll merge it now.

xpl commented 5 years ago

I've added a mention to the docs, also.