@augment-vir/common
Version:
A collection of augments, helpers types, functions, and classes for any JavaScript environment.
40 lines (39 loc) • 1.24 kB
JavaScript
import { ensureError } from '@augment-vir/core';
/**
* Measures how long (in milliseconds) the given callback takes to run to completion. By default
* this is synchronous, but it will automatically switch to async and await the callback if it
* returns a promise.
*
* @category Function
* @category Package : @augment-vir/common
* @example
*
* ```ts
* import {measureExecutionDuration} from '@augment-vir/common';
*
* const duration1 = measureExecutionDuration(() => {});
* const duration2 = await measureExecutionDuration(async () => {});
* ```
*
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function measureExecutionDuration(callback) {
const startTime = Date.now();
const result = callback();
if (result instanceof Promise) {
return new Promise(async (resolve, reject) => {
try {
await result;
const endTime = Date.now();
resolve({ milliseconds: endTime - startTime });
}
catch (caught) {
reject(ensureError(caught));
}
});
}
const endTime = Date.now();
return {
milliseconds: endTime - startTime,
};
}