Hyperlinkv0.8.0-beta.28

Chunk

Chunk.getUnsafeconsteffect/Chunk.ts:634
(index: number): <A>(self: Chunk<A>) => A
<A>(self: Chunk<A>, index: number): A

Gets an element at the specified index without returning an Option.

When to use

Use when reading from a Chunk at an index known to be in bounds and direct element access is preferred over handling Option.none.

Gotchas

Throws if the index is out of bounds.

Example (Accessing elements unsafely)

import { Chunk, Option } from "effect"

const chunk = Chunk.make("a", "b", "c", "d")

console.log(Chunk.getUnsafe(chunk, 1)) // "b"
console.log(Chunk.getUnsafe(chunk, 3)) // "d"

// Use Chunk.get when the index may be out of bounds
console.log(Option.isNone(Chunk.get(chunk, 10))) // true
unsafe
Source effect/Chunk.ts:63431 lines
export const getUnsafe: {
  (index: number): <A>(self: Chunk<A>) => A
  <A>(self: Chunk<A>, index: number): A
} = dual(2, <A>(self: Chunk<A>, index: number): A => {
  const i = Math.floor(index)
  switch (self.backing._tag) {
    case "IEmpty": {
      throw new Error(`Index out of bounds: ${i}`)
    }
    case "ISingleton": {
      if (index !== 0) {
        throw new Error(`Index out of bounds: ${i}`)
      }
      return self.backing.a
    }
    case "IArray": {
      if (i >= self.length || i < 0) {
        throw new Error(`Index out of bounds: ${i}`)
      }
      return self.backing.array[i]!
    }
    case "IConcat": {
      return i < self.left.length
        ? getUnsafe(self.left, i)
        : getUnsafe(self.right, i - self.left.length)
    }
    case "ISlice": {
      return getUnsafe(self.backing.chunk, i + self.backing.offset)
    }
  }
})
Referenced by 5 symbols