Last active
August 18, 2022 23:30
-
-
Save jsliang-art/d819f495652c2d685381d25583326fbd to your computer and use it in GitHub Desktop.
TimeTracker
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
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(); |
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
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