• Stars
    star
    302
  • Rank 138,030 (Top 3 %)
  • Language
    JavaScript
  • Created almost 13 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Nice text table for Node.js

Easy table

Nice utility for rendering text tables with javascript.

Usage

var Table = require('easy-table')

var data = [
  { id: 123123, desc: 'Something awesome', price: 1000.00 },
  { id: 245452, desc: 'Very interesting book', price: 11.45},
  { id: 232323, desc: 'Yet another product', price: 555.55 }
]

var t = new Table

data.forEach(function(product) {
  t.cell('Product Id', product.id)
  t.cell('Description', product.desc)
  t.cell('Price, USD', product.price, Table.number(2))
  t.newRow()
})

console.log(t.toString())

The script above will render:

Product Id  Description            Price, USD
----------  ---------------------  ----------
123123      Something awesome         1000.00
245452      Very interesting book       11.45
232323      Yet another product        555.55

t.printTransposed() returns

Product Id  : 245452                : 232323              : 123123
Description : Very interesting book : Yet another product : Something awesome
Price, USD  : 11.45                 : 555.55              : 1000.00

t.print() shows just rows you pushed and nothing more

123123  Something awesome      1000.00
245452  Very interesting book    11.45
232323  Yet another product     555.55

How it works

The full signature of .cell() is:

t.cell(column, value, printer)

Rendering occures in two phases. At the first phase printer is called to get the minimal width required to fit the cell content. At the second phase printer is called again with additional width parameter to get actual string to render.

For example, here is how currency printer might be defined

function currency(val, width) {
  var str = val.toFixed(2)
  return width ? Table.padLeft(str, width) : str
}

Table.print()

When you already have an array, explicit table instantiation and iteration becomes an overhead. For such cases it is convenient to use Table.print().

console.log(Table.print(data))
id      desc                   price
------  ---------------------  ------
123123  Something awesome      1000
245452  Very interesting book  11.45
232323  Yet another product    555.55

It is possible to pass some options

Table.print(data, {
  desc: {name: 'description'}
  price: {printer: Table.number(2)}
})
id      description            price
------  ---------------------  -------
123123  Something awesome      1000.00
245452  Very interesting book    11.45
232323  Yet another product     555.55

or have a full control over rendering

Table.print(data, function(item, cell) {
  cell('Product id', item.id)
  cell('Price, USD', item.price)
}, function(table) {
  return table.print()
})

Table.print() also accepts objects

Table.print(data[0])
id    : 123123
desc  : Something awesome
price : 1000

Sorting

You can sort a table by calling .sort(), and optionally passing in a list of column names to sort on (by default uses all columns), or a custom comparator function. It is also possible to specify the sort order. For example:

t.sort(['Price, USD|des']) // will sort in descending order
t.sort(['Price, USD|asc']) // will sort in ascending order
t.sort(['Price, USD']) // sorts in ascending order by default

Totaling

Easy table can help to calculate and render totals:

t.total('Price, USD')
Product Id  Description            Price, USD
----------  ---------------------  ----------
245452      Very interesting book       11.45
232323      Yet another product        555.55
123123      Something awesome         1000.00
----------  ---------------------  ----------
                                      1567.00

Here is a more elaborate example

t.total('Price, USD', {
  printer: Table.aggr.printer('Avg: ', currency),
  reduce: Table.aggr.avg,
  init: 0
})

// or alternatively

t.total('Price, USD', {
  printer: function(val, width) {
    return padLeft('Avg: ' + currency(val), width)
  },
  reduce: function(acc, val, idx, len) {
    acc = acc + val
    return idx + 1 == len ? acc/len : acc
  }
})
Product Id  Description            Price, USD
----------  ---------------------  -----------
245452      Very interesting book        11.45
232323      Yet another product         555.55
123123      Something awesome          1000.00
----------  ---------------------  -----------
                                   Avg: 522.33

Installation

via npm

$ npm install easy-table

License

(The MIT License)

Copyright (c) 2015 Eldar Gabdullin [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

load-script

Dynamic script loading
JavaScript
146
star
2

node-fake-fs

Fake node.js file system for testing
JavaScript
32
star
3

component-as-module

Require components from node programs
JavaScript
19
star
4

easy-app

Structure for large and small applications
JavaScript
15
star
5

agent-next

Simple, flexible, fun to use HTTP agent with nice API and clean implementation
JavaScript
12
star
6

LT-Opener

LightTable plugin that helps to open terminals, dirs and files
JavaScript
11
star
7

translit

Text transliteration util
JavaScript
11
star
8

translit-russian

Russian transliteration map
JavaScript
10
star
9

parse-fn-args

Parse function arguments
JavaScript
9
star
10

make-flow

Make style control flow
JavaScript
8
star
11

connect-views

Serve your jades, markdowns, lesses, etc like static files
JavaScript
5
star
12

google-maps

Load google maps from JavaScript
JavaScript
5
star
13

the-box

Deprecated (see easy-app instead)
JavaScript
4
star
14

reuse.js

Funky way to extend your objects
JavaScript
3
star
15

arabic-translit

Non-traditional, non-keyboard-macro, fluent transliteration for arabic language.
JavaScript
3
star
16

heap

Javascript implementation of Binary heap data structure
JavaScript
3
star
17

component-npm-post-install

Post install script for npm(1) which makes components consumable from node
JavaScript
3
star
18

LT-AltTab

LightTable plugin that provides windows Alt+Tab like experience for navigation between tabs.
JavaScript
3
star
19

hooks-emitter

Event emitter, but for hooks
JavaScript
2
star
20

calc.js

Toy CLI calculator. Implementation of Pratt's top down operator precedence parsing technique.
JavaScript
2
star
21

linked-list.js

Benchmarks for linked list structure
JavaScript
2
star
22

go-async

Generator based async/await blocks with support for abortion, form of TCO and fast synchronous execution.
JavaScript
2
star
23

print.js

Mini template (format) function for html, urls, etc
JavaScript
2
star
24

express-site

Quick server for static websites
JavaScript
1
star
25

frp

Playground for FRP
JavaScript
1
star
26

easy-streaming

The way to do streaming in node.js preferred by me
JavaScript
1
star
27

dx-custom-types

Custom types generation example for HydraDX chain
TypeScript
1
star
28

sublime-settings

My settings for the Sublime Text editor
Python
1
star
29

codemirror

CodeMirror in browser editor as a component
JavaScript
1
star
30

LT-NoQuestions

Never ask "Do you want to save..?" questions :)
JavaScript
1
star
31

sandbox

Just a sandbox for new projects
1
star
32

hydradx-example

TypeScript
1
star
33

exposer.js

Compiles and bundles things for browser
JavaScript
1
star
34

async-reduce

Function for async reductions on arrays with concurrency support as well
JavaScript
1
star