Skip to content

Instantly share code, notes, and snippets.

@arcanis
Created August 24, 2017 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arcanis/a0b05b4ccd8b176cd7f8e2326c8017fc to your computer and use it in GitHub Desktop.
Save arcanis/a0b05b4ccd8b176cd7f8e2326c8017fc to your computer and use it in GitHub Desktop.
class EfficientPrinter {
constructor() {
this.lines = null;
}
render(text) {
let buffer = ``;
let oldLines = this.lines || [];
let newLines = String(text).split(/\n/g);
this.lines = newLines;
for (let y = 0; y < newLines.length; ++y)
if (y < newLines.length && newLines[y] !== oldLines[y])
buffer += `\x1b[${1+y};1H\x1b[K${newLines[y]}`;
if (newLines.length < oldLines.length)
buffer += `\x1b[${1+newLines.length};1H\x1b[J`;
process.stdout.write(buffer);
}
}
// -- demo
let lines = [];
for (let t = 0; t < process.stdout.rows; ++t)
lines[t] = randomLine();
let printer = new EfficientPrinter();
function randomLine() {
return require('crypto').randomBytes(50).toString('hex');
}
setInterval(() => {
lines[Math.floor(Math.random() * lines.length)] = randomLine();
printer.render(lines.join(`\n`));
}, 1000 / 60);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment