Skip to content

Instantly share code, notes, and snippets.

@jed jed/progress.js
Last active Mar 11, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.