# Demo 4: Advanced Language Features
# Optional chaining, error handling, async, advanced patterns

# Optional chaining
let user = { 
    profile: { 
        settings: { 
            theme: "dark" 
        } 
    } 
}

# Safe navigation
user?.profile?.settings?.theme
user?.profile?.missing?.field

let empty_user = null
empty_user?.profile?.settings?.theme

# Null coalescing
let theme = user?.profile?.settings?.theme ?? "light"
theme

let missing = user?.profile?.missing?.field ?? "default"
missing

# Try-catch error handling
try {
    let result = 10 / 0
    result
} catch {
    "Division by zero handled"
}

try {
    let arr = [1, 2, 3]
    arr[10]  # This might cause an error
} catch {
    "Array access error handled"
}

# String interpolation
let name = "Alice"
let age = 25
f"Hello, {name}! You are {age} years old."

let x = 5
let y = 3
f"The sum of {x} and {y} is {x + y}"

# Pipeline operator
let numbers = [1, 2, 3, 4, 5]
let result = numbers
    |> filter(x => x % 2 == 0)
    |> map(x => x * 2)
    |> reduce((acc, x) => acc + x, 0)
result

# Spread operator in arrays
let arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let combined = [...arr1, ...arr2]
combined

let with_extra = [0, ...arr1, 4, ...arr2, 7]
with_extra

# Range expansion
let range_array = [...1..6]
range_array

# Object spread (if supported)
let base_config = { debug: true, timeout: 1000 }
let extended_config = { ...base_config, version: "1.0" }
extended_config

# Pattern guards
let classify_number = |n| => {
    match n {
        x if x < 0 => "negative",
        0 => "zero",
        x if x < 10 => "single digit", 
        x if x < 100 => "double digit",
        _ => "large number"
    }
}

classify_number(-5)
classify_number(0)
classify_number(7)
classify_number(42)
classify_number(123)

# Array pattern matching
let analyze_array = |arr| => {
    match arr {
        [] => "empty",
        [x] => f"single element: {x}",
        [x, y] => f"pair: {x}, {y}",
        [first, ...rest] => f"starts with {first}, has {rest.length()} more",
    }
}

analyze_array([])
analyze_array([42])
analyze_array([1, 2])
analyze_array([1, 2, 3, 4, 5])