UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

34 lines (32 loc) • 1.74 kB
import { isValidNanoPattern } from "../validate/isValidNanoPattern.js"; // src/precision/parse/parseNanoseconds.ts /** * Parse a decimal string produced by `formatNanoseconds` — typically one field of a JSON * payload — back to nanoseconds since the Unix epoch. * * - Takes the string *value*, not JSON text: pass `JSON.parse(payload).observedAt`, not the * payload itself. A quoted `"\"123\""` is rejected, because the quotes are not part of a * decimal integer. * - Accepts only a canonical decimal integer — an optional `-` then digits with no leading * zeros. Exponents, fractions, hex, separators, a `+` sign and surrounding whitespace are * rejected rather than coerced, so a payload written by another language's serialiser * either reads back exactly or fails loudly. * - Rejects values outside the range `Temporal.Instant` can represent * (±8_640_000_000_000_000_000_000n). * - Returns `0n` on invalid input. `0n` is also the epoch itself — `isValidNanoPattern` * tells the two apart, and accepts exactly what this parses. * * @param value decimal string form of a nanosecond timestamp (e.g. "1710072000123456789") * @returns nanoseconds since the Unix epoch as a bigint, or 0n on invalid input * * @example parseNanoseconds("1710072000123456789") // 1710072000123456789n * @example parseNanoseconds("-1000000000") // -1000000000n * @example parseNanoseconds("1.5") // 0n * @example parseNanoseconds("1e18") // 0n * @example parseNanoseconds("8640000000000000000001") // 0n — outside the instant range * @example parseNanoseconds(1710072000123456789) // 0n — number, not string */ function parseNanoseconds(value) { return isValidNanoPattern(value) ? BigInt(value) : 0n; } export { parseNanoseconds };