UNPKG

@brimdata/zealot

Version:

The Javascript Client for Zed Lakes

121 lines (120 loc) 3.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _export(target, all) { for(var name in all)Object.defineProperty(target, name, { enumerable: true, get: all[name] }); } _export(exports, { Duration: ()=>Duration, Nanosecond: ()=>Nanosecond, Microsecond: ()=>Microsecond, Millisecond: ()=>Millisecond, Second: ()=>Second, Minute: ()=>Minute, Hour: ()=>Hour, Day: ()=>Day, Week: ()=>Week, Year: ()=>Year }); const _typeDuration = require("../types/type-duration"); const _isNull = require("../utils/is-null"); const _primitive = require("./primitive"); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } class Duration extends _primitive.Primitive { asSeconds() { if ((0, _isNull.isNull)(this._nanos)) return null; const millis = Number(this._nanos / BigInt(1e6)); return millis / 1000; } asMs() { if ((0, _isNull.isNull)(this._nanos)) return null; return Number(this._nanos / BigInt(1e6)); } asNanos() { return this._nanos; } toJS() { return this.asMs(); } constructor(value){ super(value); _defineProperty(this, "type", _typeDuration.TypeDuration); _defineProperty(this, "_nanos", void 0); if ((0, _isNull.isNull)(value)) { this._nanos = null; } else { this._nanos = parseNanos(value); } } } const parseRE = /([.0-9]+)(ns|us|ms|s|m|h|d|w|y)/g; const Nanosecond = BigInt(1); const Microsecond = BigInt(1000) * Nanosecond; const Millisecond = BigInt(1000) * Microsecond; const Second = BigInt(1000) * Millisecond; const Minute = BigInt(60) * Second; const Hour = BigInt(60) * Minute; const Day = BigInt(24) * Hour; const Week = BigInt(7) * Day; const Year = BigInt(365) * Day; const scale = { ns: Nanosecond, us: Microsecond, ms: Millisecond, s: Second, m: Minute, h: Hour, d: Day, w: Week, y: Year }; function parseNanos(s) { if (s.length === 0) return BigInt(0); let negative = false; if (s[0] === "-") { negative = true; s = s.slice(1); } let matches = s.matchAll(parseRE); let d = BigInt(0); for (const match of matches){ if (match.length !== 3) throw new Error("Invalid Duration"); const [_all, num, unitName] = match; let unit = scale[unitName]; if (num.includes(".")) { const parts = num.split("."); if (parts.length !== 2) throw new Error("Invalid Duration"); let whole = parts[0]; d += BigInt(whole) * unit; let frac = parts[1]; let extra = BigInt(0); for (let char of frac){ extra += BigInt(char) * unit; unit /= BigInt(10); } d += (extra + BigInt(5)) / BigInt(10); } else { d += BigInt(num) * unit; } } if (negative) { d *= BigInt(-1); } return d; }