@tdb/util
Version:
Shared helpers and utilities.
44 lines (38 loc) • 972 B
text/typescript
import { moment } from '../../libs';
import { value } from '../value';
export type TimerUnit = 'msec' | 'ms' | 'sec' | 's';
export type ITimer = {
startedAt: Date;
reset: () => ITimer;
elapsed: (unit?: TimerUnit) => number;
};
export function timer(start?: Date) {
let startedAt = start || new Date();
const api: ITimer = {
startedAt,
reset() {
startedAt = new Date();
return api;
},
elapsed(unit: TimerUnit = 'msec') {
const duration = elapsed(startedAt);
switch (unit) {
case 'ms':
case 'msec':
return duration.asMilliseconds();
case 's':
case 'sec':
return value.round(duration.asSeconds(), 1);
default:
throw new Error(`Unit '${unit}' not supported `);
}
},
};
return api;
}
/**
* Retrieves the elapsed milliseconds from the given date.
*/
export function elapsed(from: Date) {
return moment.duration(moment().diff(from));
}