Skip to content

Instantly share code, notes, and snippets.

@jamesliu96
Last active October 27, 2020 11:29
Show Gist options
  • Save jamesliu96/fa7c8b5acad337b29d0716cedd434b69 to your computer and use it in GitHub Desktop.
Save jamesliu96/fa7c8b5acad337b29d0716cedd434b69 to your computer and use it in GitHub Desktop.
class Hourglass {
private ticker: ([number] | [number, number])[] = [];
public tic() {
const d = this.ticker.slice(-1)[0];
if (!this.ticker.length || d[1]) {
this.ticker.push([Date.now()]);
}
}
public tok() {
const d = this.ticker.slice(-1)[0];
if (this.ticker.length && !d[1]) {
d[1] = Date.now();
}
}
public sum() {
return (this.ticker.map((v, idx) =>
idx === v[1] ? v : [v[0], Date.now()]
) as [number, number][]).reduce((acc, v) => acc + (v[1] - v[0]), 0);
}
}
class Hourglass2 {
private start = 0;
private total = 0;
public tic() {
this.start = Date.now();
}
public tok() {
if (this.start) {
this.total += Date.now() - this.start;
this.start = 0;
}
}
public sum() {
this.tok();
return this.total;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment