Rosetta Code

Stack

Model a small LIFO stack with push, pop, and peek over an array-backed store.

Source rosettacode/popular/stack.vibe
# title: Stack
# source: https://rosettacode.org/wiki/Stack
# category: Rosetta Code
# difficulty: Easy
# summary: Model a small LIFO stack with push, pop, and peek over an array-backed store.
# tags: popular, stack, arrays, data-structures
# vibe: 0.2

def new_stack
  {
    items: []
  }
end

def push(stack, value)
  stack[:items] = stack[:items].push(value)
  stack
end

def peek(stack)
  items = stack[:items]

  if items.empty?
    nil
  else
    items[items.length - 1]
  end
end

def pop(stack)
  popped = stack[:items].pop
  stack[:items] = popped[:array]
  {
    stack: stack,
    value: popped[:popped]
  }
end

def run
  stack = new_stack
  stack = push(stack, "red")
  stack = push(stack, "green")
  stack = push(stack, "blue")
  top_before_pop = peek(stack)
  popped = pop(stack)
  stack = popped[:stack]

  {
    peek_before_pop: top_before_pop,
    popped: popped[:value],
    peek_after_pop: peek(stack),
    size_after_pop: stack[:items].length,
    contents: stack[:items]
  }
end
Output
Press run to execute run from this example.
rosetta-code popular stack arrays data-structures browser-runner