From 5f3c5e3b14ff31c681b690193d21989a08b3048a Mon Sep 17 00:00:00 2001 From: Sasha Koshka Date: Fri, 9 Sep 2022 01:39:04 -0400 Subject: [PATCH] Added cool little generic stack --- types/stack.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 types/stack.go diff --git a/types/stack.go b/types/stack.go new file mode 100644 index 0000000..1dcfcd9 --- /dev/null +++ b/types/stack.go @@ -0,0 +1,31 @@ +package types + +// Stack is a generic stack data structure. +type Stack[VALUE any] []VALUE + +// Push adds a value to the top of the stack. +func (stack *Stack[VALUE]) Push (value VALUE) { + *stack = append(*stack, value) +} + +// Pop removes the topmost value of the stack and returns it. +func (stack *Stack[VALUE]) Pop () (value VALUE) { + if len(*stack) < 1 { + panic("can't pop off of empty stack") + } + + newLength := len(*stack) - 1 + value = (*stack)[newLength] + *stack = (*stack)[:newLength] + return +} + +// Top returns the value on top of the stack. +func (stack Stack[VALUE]) Top () (value VALUE) { + if len(stack) < 1 { + panic("can't get top of empty stack") + } + + value = stack[len(stack) - 1] + return +}