Skip to content

Instantly share code, notes, and snippets.

@jed
Last active March 11, 2016 08:37
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jed/4dd88231e113d086e239 to your computer and use it in GitHub Desktop.
Save jed/4dd88231e113d086e239 to your computer and use it in GitHub Desktop.
Using template strings as progress bars
"use strict"
function progress(strs, current, total) {
let str = `${strs[0]}${current}${strs[1]}${total}${strs[2]}`
let ratio = Math.min(Math.max(current / total, 0), 1)
let length = Math.floor(ratio * str.length)
let pattern = new RegExp(`^.{${length}}`)
return str.replace(pattern, "\x1b[4m$&\x1b[0m")
}
void function loop(current, total) {
let message = progress`${current} of ${total} pages crawled`
process.stderr.write(` ${message}`)
process.stderr.clearLine(1)
if (current == total) return process.stderr.write(": done.\n\n")
process.stderr.cursorTo(0)
let interval = 0 | Math.random() * 50
setTimeout(loop, interval, ++current, total)
}(0, 200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment