Skip to content

Instantly share code, notes, and snippets.

@khpatel4991
Last active July 1, 2019 23:22
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 khpatel4991/e34b57203477e4686c38ffe2da2c361b to your computer and use it in GitHub Desktop.
Save khpatel4991/e34b57203477e4686c38ffe2da2c361b to your computer and use it in GitHub Desktop.
Inline progress bar
import * as readline from 'readline'
import { performance } from 'perf_hooks';
const delay = <T>(ms: number, returnValue: T = undefined): Promise<T> =>
new Promise(resolve => setTimeout(() => resolve(returnValue), ms));
const showPercentage = (percentage: string) => {
readline.cursorTo(process.stdout, 0, null);
let text = `working ... ${percentage}%`
process.stdout.write(text);
}
const abc = async (items: number[]) => {
const total = items.length;
for (let i = 1; i <= total; i++) {
await delay(15)
showPercentage(((i / total) * 100).toFixed(2));
}
process.stdout.write("\n");
}
const main = async () => {
try {
const items = Array.from(Array(5000), (_, i) => i)
const start = performance.now();
await abc(items);
const elapsed = performance.now() - start;
console.log(`Total time for ${items.length} items: ${elapsed}ms.`);
console.log(`Avg Time for each item: ${elapsed / items.length}ms.`);
return 'done';
} catch (e) {
return `not done. Error: ${e.message}`;
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment