lloyAlloy on GitHub
Heap
Docs

Heap

Updated
Heap<T>
import { Heap } from "@alloy/std/collections"

type Node = { cost: number }
local open = new Heap(function(a: Node, b: Node): boolean return a.cost < b.cost end)
open:push({ cost = 3 })
print(open:pop())

A binary heap, from the std: pop yields the least value under less, which defaults to <, so numbers and strings need no comparator and tables take one. new Heap(less?) and Heap.from(t, less?) both give a Heap<T>, and Heap.from builds one from an array. A for loop reads it least first without a pop; to_array returns the items sorted.

Statics

Heap.new

Heap.new<T>(less: ((T, T) -> boolean)?): Heap<T>

An empty heap. less decides which value is least and defaults to <, so numbers and strings need none and tables take one.

import { Heap } from "@alloy/std/collections"

local open = new Heap(function(a: number, b: number) return a < b end)
open:push(3)

Heap.from

Heap.from<T>(items: { T }, less: ((T, T) -> boolean)?): Heap<T>

A heap built from an array, pushed item by item.

import { Heap } from "@alloy/std/collections"

local costs = Heap.from({ 3, 1, 2 })
print(costs:pop())

Methods

Heap:push

Heap:push(value: T)

Adds a value and sifts it up. The cost grows with the log of the size.

import { Heap } from "@alloy/std/collections"

local costs: Heap<number> = new Heap()
costs:push(3)

Heap:pop

Heap:pop(): T?

Removes the least value under less and returns it, or nil when the heap is empty.

import { Heap } from "@alloy/std/collections"

local costs = Heap.from({ 3, 1, 2 })
print(costs:pop())

Heap:peek

Heap:peek(): T?

The least value without removing it, or nil when the heap is empty.

import { Heap } from "@alloy/std/collections"

local costs = Heap.from({ 3, 1 })
print(costs:peek())

Heap:len

Heap:len(): number

The number of values held.

import { Heap } from "@alloy/std/collections"

local costs = Heap.from({ 3, 1 })
print(costs:len())

Heap:is_empty

Heap:is_empty(): boolean

Whether the heap holds nothing.

import { Heap } from "@alloy/std/collections"

local costs: Heap<number> = new Heap()
print(costs:is_empty())

Heap:clear

Heap:clear()

Drops every value.

import { Heap } from "@alloy/std/collections"

local costs = Heap.from({ 3, 1 })
costs:clear()

Heap:to_array

Heap:to_array(): T[]

The values sorted under less, as a new array. The heap keeps its own; a for loop over the heap reads the same order without a pop.

import { Heap } from "@alloy/std/collections"

local costs = Heap.from({ 3, 1, 2 })
print(costs:to_array():first())

Heap:to_table

Heap:to_table(): { T }

The heap's own table, not a copy: a write through it changes the heap. The order is heap order, not sorted order, and a write breaks what pop needs; to_array sorts a copy.

import { Heap } from "@alloy/std/collections"

local costs = Heap.from({ 3, 1, 2 })
local t = costs:to_table()
print(#t)