Stack
A generic LIFO (Last-In, First-Out) data structure that stores items in a stack, allowing elements to be added and removed only from the top.
It is ideal for flow control, expression evaluation, parsing, and other situations where the last value inserted must be the first one retrieved.
provides a simple and efficient way to manage mutable collections, with tunable memory release behavior through the shrinkFactor parameter
Import
_ <- fat.extra.Stack
Constructor
| Name |
Signature |
Brief |
| Stack |
(stack: List = []) |
Creates a stack optionally initialized from an existing list |
when initialized with a list, the top of the stack will correspond to the last element of the list
Control parameter
| Name |
Type |
Default |
Description |
| shrinkFactor |
Number |
1.5 |
Defines the automatic contraction factor of the internal list |
Typical values for shrinkFactor
| Value |
Effect |
| 1.0 |
Shrinks the stack on every pop (faster memory release) |
| 1.5 |
Balanced between speed and memory usage (default) |
| 2.0 |
Reduces cleanup operations but holds memory longer |
| infinity |
Disables automatic shrinking |
Prototype members
| Name |
Signature |
Brief |
| isEmpty |
<> Boolean |
Return true if stack is empty |
| nonEmpty |
<> Boolean |
Return true if stack is not empty |
| size |
<> Number |
Return the number of items in the stack |
| toText |
<> Text |
Return 'Stack' as text literal |
| some |
<> Option |
Wrap value into Option |
| push |
(value: Any): Void |
Add a value to the top of the stack |
| pop |
<> Any |
Remove and return the top item; throws if empty |
| peek |
<> Any |
Return the top item without removing it |
| toList |
<> List |
Return a shallow copy of the stack as a list |
Example
_ <- fat.extra.Stack
stack = Stack()
stack.push("{")
stack.push("[")
stack.pop # returns "["
stack.peek # returns "{"
stack.isEmpty # returns false
stack.size # returns 1
Notes
Stack is not reentrant - when used in asynchronous contexts, its operations must be manually protected with async.atomic, for example:
async.atomic(-> stack.push(value))
See also