Hyperlinkv0.8.0-beta.28

Duration

Duration.divideconsteffect/Duration.ts:1306
(by: number): (self: Duration) => Option.Option<Duration>
(self: Duration, by: number): Option.Option<Duration>

Divides a Duration by a finite, non-zero number safely.

Details

Returns Option.none() for zero, negative zero, or non-finite divisors. For nanosecond-backed durations, also returns Option.none() when the divisor cannot be converted to a bigint, such as a fractional divisor.

Example (Safely dividing durations)

import { Duration, Option } from "effect"

const d = Duration.divide(Duration.seconds(10), 2)
console.log(Option.map(d, Duration.toSeconds)) // Some(5)

Duration.divide(Duration.seconds(10), 0) // None
math
export const divide: {
  (by: number): (self: Duration) => Option.Option<Duration>
  (self: Duration, by: number): Option.Option<Duration>
} = dual(
  2,
  (self: Duration, by: number): Option.Option<Duration> => {
    if (!Number.isFinite(by)) return Option.none()
    if (by === 0 || Object.is(by, -0)) return Option.none()
    return match(self, {
      onMillis: (millis) => Option.some(make(millis / by)),
      onNanos: (nanos) => {
        try {
          return Option.some(make(nanos / BigInt(by)))
        } catch {
          return Option.none()
        }
      },
      onInfinity: () => Option.some(by > 0 ? infinity : negativeInfinity),
      onNegativeInfinity: () => Option.some(by > 0 ? negativeInfinity : infinity)
    })
  }
)