Hyperlinkv0.8.0-beta.28

Iterable

Iterable.headconsteffect/Iterable.ts:506
<A>(self: Iterable<A>): Option<A>

Gets the first element of a Iterable safely, or None if the Iterable is empty.

Example (Getting the first element)

import { Iterable, Option } from "effect"

const numbers = [1, 2, 3]
console.log(Iterable.head(numbers)) // Option.some(1)

const empty = Iterable.empty<number>()
console.log(Iterable.head(empty)) // Option.none()

// Safe way to get first element
const firstEven = Iterable.head(
  Iterable.filter([1, 3, 4, 5], (x) => x % 2 === 0)
)
console.log(firstEven) // Option.some(4)

// Use with Option methods
const doubled = Option.map(Iterable.head([5, 10, 15]), (x) => x * 2)
console.log(doubled) // Option.some(10)
getters
export const head = <A>(self: Iterable<A>): Option<A> => {
  const iterator = self[Symbol.iterator]()
  const result = iterator.next()
  return result.done ? O.none() : O.some(result.value)
}