Skip to content

API Reference

This document provides a comprehensive reference for all methods available in Harneet's enhanced collections module.

Constructor Functions

Basic Collections

Basic Collections
1
2
3
4
5
6
7
8
collections.new_stack() -> Stack
collections.new_queue() -> Queue
collections.new_set() -> Set
collections.new_linked_list() -> LinkedList
collections.new_bst() -> BinarySearchTree
collections.new_bst(compareFn) -> BinarySearchTree
collections.new_array() -> Array
collections.new_map() -> Map

Concurrent Collections

Concurrent Collections
1
2
3
4
5
6
collections.new_concurrent_stack() -> ConcurrentStack
collections.new_concurrent_queue() -> ConcurrentQueue
collections.new_concurrent_set() -> ConcurrentSet
collections.new_concurrent_linked_list() -> ConcurrentLinkedList
collections.new_concurrent_bst() -> ConcurrentBinarySearchTree
collections.new_concurrent_map() -> ConcurrentMap

Factory Functions

Factory Functions
1
2
3
4
5
collections.array_from_slice(slice) -> Array
collections.linked_list_from_array(array) -> LinkedList
collections.bst_from_array(array) -> BinarySearchTree
collections.set_from_array(array) -> Set
collections.map_from_entries(entries) -> Map

Stack API

Core Operations

Method Parameters Returns Time Complexity Description
push(item) item: any void O(1) amortized Add item to top of stack
pop() - any \| Error O(1) Remove and return top item
peek() - any \| null O(1) View top item without removing
is_empty() - bool O(1) Check if stack is empty
size() - int O(1) Get number of items
clear() - void O(1) Remove all items

Enhanced Operations

Method Parameters Returns Time Complexity Description
reserve(capacity) capacity: int void O(1) Pre-allocate memory
to_array() - Array O(n) Convert to array
iterator() - Iterator O(1) Get iterator
inspect() - string O(n) String representation

Example Usage

Stack Usage
var stack = collections.new_stack()
stack.reserve(100)        // Pre-allocate for performance
stack.push(42)
stack.push("hello")

if !stack.is_empty() {
    var top = stack.peek()    // "hello"
    var item = stack.pop()    // "hello"
}

var array = stack.to_array()  // [42]

Queue API

Core Operations

Method Parameters Returns Time Complexity Description
enqueue(item) item: any void O(1) amortized Add item to rear
dequeue() - any \| Error O(1) Remove and return front item
peek() - any \| null O(1) View front item without removing
is_empty() - bool O(1) Check if queue is empty
size() - int O(1) Get number of items
clear() - void O(1) Remove all items

Enhanced Operations

Method Parameters Returns Time Complexity Description
reserve(capacity) capacity: int void O(1) Pre-allocate circular buffer
to_array() - Array O(n) Convert to array
iterator() - Iterator O(1) Get iterator
inspect() - string O(n) String representation

Example Usage

Queue Usage
1
2
3
4
5
6
7
var queue = collections.new_queue()
queue.reserve(50)         // Pre-allocate circular buffer
queue.enqueue("first")
queue.enqueue("second")

var front = queue.peek()      // "first"
var item = queue.dequeue()    // "first"

Set API

Core Operations

Method Parameters Returns Time Complexity Description
add(item) item: any bool O(1) average Add item to set, returns true if new
remove(item) item: any bool O(1) average Remove item, returns true if found
contains(item) item: any bool O(1) average Check if item exists
is_empty() - bool O(1) Check if set is empty
size() - int O(1) Get number of items
clear() - void O(1) Remove all items

Set Theory Operations

Method Parameters Returns Time Complexity Description
union(other) other: Set Set O(n + m) Union of two sets
intersection(other) other: Set Set O(min(n,m)) Intersection of two sets
difference(other) other: Set Set O(n) Elements in this set but not other
symmetric_difference(other) other: Set Set O(n + m) Elements in either set but not both
is_subset(other) other: Set bool O(n) Check if this is subset of other
is_superset(other) other: Set bool O(m) Check if this is superset of other

Batch Operations

Method Parameters Returns Time Complexity Description
add_all(items) items: Array void O(n) Add multiple items
remove_all(items) items: Array void O(n) Remove multiple items
to_array() - Array O(n) Convert to array
iterator() - Iterator O(1) Get iterator

Example Usage

Set Usage
var set1 = collections.new_set()
set1.add("apple")
set1.add("banana")

var set2 = collections.new_set()
set2.add("banana")
set2.add("cherry")

var union = set1.union(set2)          // {"apple", "banana", "cherry"}
var intersection = set1.intersection(set2)  // {"banana"}
var difference = set1.difference(set2)      // {"apple"}

LinkedList API

Core Operations

Method Parameters Returns Time Complexity Description
add_first(item) item: any void O(1) Add item to front
add_last(item) item: any void O(1) Add item to rear
add_at(index, item) index: int, item: any bool \| Error O(n) Add item at position
remove_first() - any \| Error O(1) Remove and return first item
remove_last() - any \| Error O(1) Remove and return last item
remove_at(index) index: int any \| Error O(n) Remove and return item at position
remove(item) item: any bool O(n) Remove first occurrence of item

Access Operations

Method Parameters Returns Time Complexity Description
get(index) index: int any \| Error O(n) Get item at position
index_of(item) item: any int O(n) Find index of item (-1 if not found)
last_index_of(item) item: any int O(n) Find last index of item
contains(item) item: any bool O(n) Check if item exists
is_empty() - bool O(1) Check if list is empty
size() - int O(1) Get number of items

Iteration and Conversion

Method Parameters Returns Time Complexity Description
iterator() - Iterator O(1) Get forward iterator
reverse_iterator() - Iterator O(1) Get reverse iterator
to_array() - Array O(n) Convert to array
clear() - void O(1) Remove all items

Functional Operations

Method Parameters Returns Time Complexity Description
map(fn) fn: function(any) -> any LinkedList O(n) Transform each element
filter(fn) fn: function(any) -> bool LinkedList O(n) Filter elements
reduce(fn, initial) fn: function(any, any) -> any, initial: any any O(n) Reduce to single value
find(fn) fn: function(any) -> bool any \| null O(n) Find first matching element

Example Usage

LinkedList Usage
var list = collections.new_linked_list()
list.add_last(1)
list.add_last(2)
list.add_first(0)         // [0, 1, 2]

list.add_at(1, 0.5)       // [0, 0.5, 1, 2]
var item = list.get(2)    // 1
var index = list.index_of(2)  // 3

var doubled = list.map(((x) =>) x * 2)     // [0, 1, 2, 4]
var evens = list.filter(((x) =>) x % 2 == 0)  // [0, 2]

BinarySearchTree API

Core Operations

Method Parameters Returns Time Complexity Description
insert(item) item: any void O(log n) avg Insert item maintaining BST property
remove(item) item: any bool O(log n) avg Remove item, returns true if found
contains(item) item: any bool O(log n) avg Check if item exists
min() - any \| null O(log n) Get minimum value
max() - any \| null O(log n) Get maximum value
is_empty() - bool O(1) Check if tree is empty
size() - int O(1) Get number of nodes
height() - int O(1) Get tree height
clear() - void O(1) Remove all nodes

Traversal Operations

Method Parameters Returns Time Complexity Description
in_order_traversal() - Array O(n) Get sorted array of values
pre_order_traversal() - Array O(n) Get pre-order array
post_order_traversal() - Array O(n) Get post-order array
level_order_traversal() - Array O(n) Get level-order array
in_order_iterator() - Iterator O(1) Get in-order iterator

Advanced Operations

Method Parameters Returns Time Complexity Description
successor(item) item: any any \| null O(log n) Get next larger value
predecessor(item) item: any any \| null O(log n) Get next smaller value
range_query(min, max) min: any, max: any Array O(log n + k) Get values in range
values_less_than(value) value: any Array O(n) Get all values less than given
values_greater_than(value) value: any Array O(n) Get all values greater than given
depth(item) item: any int O(log n) Get depth of item
is_balanced() - bool O(n) Check if tree is balanced

Example Usage

BST Usage
var tree = collections.new_bst()
tree.insert(50)
tree.insert(30)
tree.insert(70)

var min = tree.min()      // 30
var max = tree.max()      // 70
var sorted = tree.in_order_traversal()  // [30, 50, 70]

var range = tree.range_query(25, 60)    // [30, 50]
var successor = tree.successor(30)      // 50

Enhanced Array API

Core Operations (Inherited)

All standard array operations plus:

Method Parameters Returns Time Complexity Description
reserve(capacity) capacity: int void O(1) Pre-allocate memory
shrink() - void O(1) Reduce memory footprint
insert_at(index, item) index: int, item: any bool \| Error O(n) Insert item at position
remove_at(index) index: int any \| Error O(n) Remove item at position
index_of(item) item: any int O(n) Find index of item
last_index_of(item) item: any int O(n) Find last index of item
reverse() - void O(n) Reverse array in place

Functional Operations

Method Parameters Returns Time Complexity Description
map(fn) fn: function(any) -> any Array O(n) Transform each element
filter(fn) fn: function(any) -> bool Array O(n) Filter elements
reduce(fn, initial) fn: function(any, any) -> any, initial: any any O(n) Reduce to single value
find(fn) fn: function(any) -> bool any \| null O(n) Find first matching element
find_index(fn) fn: function(any) -> bool int O(n) Find index of first match
every(fn) fn: function(any) -> bool bool O(n) Check if all elements match
some(fn) fn: function(any) -> bool bool O(n) Check if any element matches

Sorting Operations

Method Parameters Returns Time Complexity Description
sort() - void O(n log n) Sort using default comparison
sort_by(fn) fn: function(any, any) -> int void O(n log n) Sort using custom comparison
is_sorted() - bool O(n) Check if array is sorted

Example Usage

Array Usage
var array = collections.new_array()
array.reserve(100)        // Pre-allocate
array.append(3)
array.append(1)
array.append(4)

array.insert_at(1, 2)     // [3, 2, 1, 4]
array.sort()              // [1, 2, 3, 4]

var doubled = array.map(((x) =>) x * 2)        // [2, 4, 6, 8]
var evens = array.filter(((x) =>) x % 2 == 0)  // [2, 4]
var sum = array.reduce(|acc, x| acc + x, 0)  // 10

Enhanced Map API

Core Operations (Inherited)

All standard map operations plus:

Method Parameters Returns Time Complexity Description
reserve(capacity) capacity: int void O(1) Pre-allocate buckets
contains_key(key) key: any bool O(1) average Check if key exists
contains_value(value) value: any bool O(n) Check if value exists
keys() - Array O(n) Get all keys
values() - Array O(n) Get all values
entries() - Array O(n) Get key-value pairs
merge(other) other: Map void O(m) Merge another map

Functional Operations

Method Parameters Returns Time Complexity Description
filter(fn) fn: function(key, value) -> bool Map O(n) Filter key-value pairs
map_values(fn) fn: function(value) -> any Map O(n) Transform values
map_keys(fn) fn: function(key) -> any Map O(n) Transform keys
for_each(fn) fn: function(key, value) -> void void O(n) Execute function for each pair

Example Usage

Map Usage
var map = collections.new_map()
map.reserve(50)           // Pre-allocate buckets
map.set("name", "Alice")
map.set("age", 30)

var has_name = map.contains_key("name")     // true
var has_alice = map.contains_value("Alice") // true

var keys = map.keys()     // ["name", "age"]
var values = map.values() // ["Alice", 30]

var filtered = map.filter(|k, v| k.starts_with("n"))  // {"name": "Alice"}

Concurrent Collections API

All concurrent collections have the same API as their non-concurrent counterparts, with additional thread-safety guarantees:

Additional Methods

Method Parameters Returns Description
get_stats() - ConcurrentStats Get performance statistics
try_lock() - bool Attempt to acquire lock
unlock() - void Release lock

Performance Statistics

Performance Stats
1
2
3
4
5
6
struct ConcurrentStats {
    read_count: int
    write_count: int
    contention_count: int
    avg_wait_time: float
}

Example Usage

Concurrent Map Usage
var concurrent_map = collections.new_concurrent_map()

// Thread-safe operations
do {
    for i in range(1000) {
        concurrent_map.set("key_" + i.to_string(), i)
    }
}

do {
    for i in range(1000) {
        var value = concurrent_map.get("key_" + i.to_string())
    }
}

var stats = concurrent_map.get_stats()
fmt.Println("Reads:", stats.read_count)
fmt.Println("Writes:", stats.write_count)

Iterator API

All collections that support iteration provide iterators with this interface:

Iterator Methods

Method Parameters Returns Description
has_next() - bool Check if more elements available
next() - any \| Error Get next element
remove() - bool Remove current element (if supported)
reset() - void Reset iterator to beginning

Example Usage

Conversion Examples
var collection = collections.new_linked_list()
collection.add_last(1)
collection.add_last(2)
collection.add_last(3)

var iter = collection.iterator()
for iter.has_next() {
    var item = iter.next()
    fmt.Println(item)

    if item == 2 {
        iter.remove()  // Remove current item
    }
}

Error Handling

All collection methods follow consistent error handling patterns:

Error Types

  • IndexOutOfBounds: Invalid array/list index
  • EmptyCollection: Operation on empty collection
  • InvalidType: Non-hashable type in Set/Map
  • ConcurrentModification: Iterator invalidated by modification
  • CapacityExceeded: Collection size limit reached

Error Checking

Error Checking
var result = collection.get(index)
if result.type() == "ERROR" {
    fmt.Println("Error:", result.message())
    return
}

// Safe operations
if !collection.is_empty() {
    var item = collection.pop()  // Safe
}

// Bounds checking
if index >= 0 && index < collection.size() {
    var item = collection.get(index)  // Safe
}

Performance Guidelines

Time Complexity Quick Reference

  • O(1): Stack/Queue push/pop, Set/Map add/get/remove, Array access
  • O(log n): BST operations, sorted operations
  • O(n): Linear search, iteration, array insertion/deletion
  • O(n log n): Sorting operations
  • O(n + m): Set union operations

Memory Usage Guidelines

  • Pre-allocate collections when size is known
  • Use appropriate data structure for access patterns
  • Consider memory overhead for pointer-based structures
  • Monitor concurrent collection contention

Best Practices

  1. Choose the right data structure for your access patterns
  2. Pre-allocate capacity when collection size is known
  3. Use iterators instead of index-based loops for linked structures
  4. Use concurrent collections only when needed for multi-threading
  5. Handle errors appropriately for robust applications

This API reference provides comprehensive coverage of all collection methods with their signatures, complexity characteristics, and usage examples.