Hyperlinkv0.8.0-beta.28

Duration

Duration.divideUnsafeconsteffect/Duration.ts:1361
(by: number): (self: Duration) => Duration
(self: Duration, by: number): Duration

Divides a Duration by a number using fallback rules instead of returning an Option.

When to use

Use when dividing a Duration should return Duration.zero or signed infinity for invalid cases instead of forcing callers to handle Option.none.

Details

Non-finite divisors return Duration.zero. Division by positive or negative zero can produce signed infinity for non-zero finite durations, while zero or infinite durations divided by zero produce Duration.zero. Nanosecond-backed durations return Duration.zero when the divisor cannot be converted to a bigint.

Example (Dividing durations unsafely)

import { Duration } from "effect"

const half = Duration.divideUnsafe(Duration.seconds(10), 2)
console.log(Duration.toSeconds(half)) // 5

const infinite = Duration.divideUnsafe(Duration.seconds(10), 0)
console.log(Duration.toMillis(infinite)) // Infinity
math
export const divideUnsafe: {
  (by: number): (self: Duration) => Duration
  (self: Duration, by: number): Duration
} = dual(
  2,
  (self: Duration, by: number): Duration => {
    if (!Number.isFinite(by)) return zero
    return match(self, {
      onMillis: (millis) => make(millis / by),
      onNanos: (nanos) => {
        if (Object.is(by, 0) || Object.is(by, -0)) {
          if (nanos === bigint0) return zero
          // match IEEE 754: same sign → +infinity, different sign → -infinity
          const positiveNanos = nanos > bigint0
          const positiveZero = Object.is(by, 0)
          return (positiveNanos === positiveZero) ? infinity : negativeInfinity
        }
        try {
          return make(nanos / BigInt(by))
        } catch {
          return zero
        }
      },
      onInfinity: () => by > 0 ? infinity : by < 0 ? negativeInfinity : zero,
      onNegativeInfinity: () => by > 0 ? negativeInfinity : by < 0 ? infinity : zero
    })
  }
)