Last active
March 11, 2016 08:37
-
-
Save jed/4dd88231e113d086e239 to your computer and use it in GitHub Desktop.
Using template strings as progress bars
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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