import {Milliseconds, NANOS_IN_MS, Nanoseconds, NanoTime, TimeAndRemainder} from './constants';
import {NanoTimeMeasurement} from './primitives';
export function rawNanos(nanos: NanoTime): bigint {
let result;
if (nanos instanceof NanoTimeMeasurement) {
result = (nanos as NanoTimeMeasurement).asNanoseconds();
}
else if (typeof nanos === 'bigint' || result instanceof BigInt) {
result = nanos;
}
else Eif (nanos && 'asNanoseconds' in (nanos as any)) {
result = (nanos as any).asNanoseconds();
}
return result;
}
export function millisAsNanoString(milllis: Milliseconds, postfix: '' | 'n' = '') {
return `${milllis}000000${postfix}`;
}
export function nanosAsString(nanos: NanoTime, postfix: '' | 'n' = ''): string {
return `${rawNanos(nanos)}${postfix}`;
}
export function millisAsNanos(millis: Milliseconds): bigint {
return NANOS_IN_MS * BigInt(millis);
}
export function timePart(nanos: NanoTime, unit: Nanoseconds): TimeAndRemainder {
const count = rawNanos(nanos) / unit;
const remainder = rawNanos(nanos) % unit;
return [count, remainder];
}
export function timePartValue(nanos: NanoTime, unit: Nanoseconds): bigint {
return timePart(nanos, unit)[0];
}
export function timeParts(nanos: NanoTime, parts: { name: string; unit: bigint }[]): Record<string, bigint> {
parts.sort((left, right) => left.unit > right.unit ? -1 : 1);
let remainder: bigint = rawNanos(nanos);
const result = {};
for (const part of parts) {
const [val, remain] = timePart(remainder, part.unit);
result[part.name] = val;
remainder = remain;
}
return result;
}
export function nanosAsMillis(nanos: NanoTime, truncate = false): Milliseconds {
const result = Number(rawNanos(nanos) / NANOS_IN_MS);
return truncate ? Math.floor(result) : result;
}
export function nanosAsJsDate(nanos: NanoTime): Date {
return new Date(Number(nanosAsMillis(nanos)));
}
|