Skip to content

Instantly share code, notes, and snippets.

@jsliang-art
Last active August 18, 2022 23:30
Show Gist options
  • Save jsliang-art/d819f495652c2d685381d25583326fbd to your computer and use it in GitHub Desktop.
Save jsliang-art/d819f495652c2d685381d25583326fbd to your computer and use it in GitHub Desktop.
TimeTracker
function initTimeTracker() {
const stack = [];
function getPadding() {
return `${Array.from({ length: stack.length - 1 })
.map(() => "|")
.join("")}+`;
}
// Push the current timestamp to stack
function push(label) {
stack.push({ label, timestamp: +new Date() });
console.log(`${getPadding()} ${label} START`);
}
// Pop the previous timestamp from stack and calculate
// the difference between the current timestamp
function pop() {
const padding = getPadding();
const prev = stack.pop();
if (!prev) {
console.error(`Stack is empty. Did you forget to call push() first?`);
return;
}
const currTimestamp = +new Date();
const diff = currTimestamp - prev.timestamp;
console.log(`${padding} ${prev.label} DONE: ${diff}ms`);
}
return { push, pop };
}
window.TimeTracker = initTimeTracker();
interface TimeTracker {
push: (label: string) => void;
pop: () => void;
}
function initTimeTracker(): TimeTracker {
const stack: { label: string; timestamp: number }[] = [];
function getPadding() {
return `${Array.from({ length: stack.length - 1 })
.map(() => "|")
.join("")}+`;
}
// Push the current timestamp to stack
function push(label: string) {
stack.push({ label, timestamp: +new Date() });
console.log(`${getPadding()} ${label} START`);
}
// Pop the previous timestamp from stack and calculate
// the difference between the current timestamp
function pop() {
const padding = getPadding();
const prev = stack.pop();
if (!prev) {
console.error(`Stack is empty. Did you forget to call push() first?`);
return;
}
const currTimestamp = +new Date();
const diff = currTimestamp - prev.timestamp;
console.log(`${padding} ${prev.label} DONE: ${diff}ms`);
}
return { push, pop };
}
window.TimeTracker = initTimeTracker();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment