1 | const ascension = require('ascension')
|
2 | const sort = ascension([ Number ], entry => [ entry.when ])
|
3 |
|
4 | const Isochronous = require('isochronous')
|
5 |
|
6 | class Printer {
|
7 | constructor (destructible, write, format, interval) {
|
8 | this._write = write
|
9 | this._entries = []
|
10 | this._format = format
|
11 | const isochronous = new Isochronous(interval, true, this._check.bind(this))
|
12 | destructible.durable('isochronous', isochronous.start())
|
13 | destructible.destruct(() => isochronous.stop())
|
14 | destructible.destruct(() => this._log(this._entries.splice(0).sort(sort)))
|
15 | }
|
16 |
|
17 | say (label, entry) {
|
18 | this._entries.push({ when: Date.now(), qualifier: 'prolific', label, ...entry })
|
19 | }
|
20 |
|
21 | push (envelope) {
|
22 | this._entries.push.apply(this._entries, envelope.entries)
|
23 | }
|
24 |
|
25 | _log (entries) {
|
26 | if (entries.length != 0) {
|
27 | this._write.call(null, entries.map(this._format).join('\n'))
|
28 | }
|
29 | }
|
30 |
|
31 | _check (status) {
|
32 | this._entries.sort(sort)
|
33 | const stop = status.scheduled - Math.ceil(status.interval * 1.51)
|
34 | let i, I
|
35 | for (i = 0, I = this._entries.length; i < I; i++) {
|
36 | if (this._entries[i].when > stop) {
|
37 | break
|
38 | }
|
39 | }
|
40 | this._log(this._entries.splice(0, i))
|
41 | }
|
42 | }
|
43 |
|
44 | module.exports = Printer
|