snapmetrics
Version:
Lightweight library for tracking real-time metrics and events with rolling statistics over configurable time windows.
34 lines (33 loc) • 1.15 kB
JavaScript
/**
* Converts a time window string (e.g., "1m") into milliseconds.
* @param window Time window string
* @returns Milliseconds equivalent
*/
export const parseTimeWindow = (window) => {
const match = window.match(/^(\d+)([smh])$/);
if (!match) {
throw new Error(`Invalid time window format: ${window}`);
}
const [_, value, unit] = match;
const multipliers = { s: 1000, m: 60 * 1000, h: 60 * 60 * 1000 };
return parseInt(value, 10) * multipliers[unit];
};
/**
* Swaps the first and second levels of keys in a nested object.
* @param obj Object with nested key structure to transform
* @returns Object with first and second level keys swapped
*/
export const swapLevels = (obj) => {
const result = {};
for (const [outerKey, innerObj] of Object.entries(obj)) {
for (const [innerKey, value] of Object.entries(innerObj)) {
const newOuterKey = innerKey;
const newInnerKey = outerKey;
if (!result[newOuterKey]) {
result[newOuterKey] = {};
}
result[newOuterKey][newInnerKey] = value;
}
}
return result;
};