← Home
The Stack Store is a data structure for storing items in a last-in, first-out (LIFO) manner. It offers methods to add or remove items, observe changes, and check the current stack size.
To integrate the Stack Store into your project:
import { createStackStore } from '@yobta/stores'
Initialize the Stack Store with an initial state:
const initialState: string[] = []
const myStack = createStackStore<string>(initialState)
Use the push
method to add items. This method returns the new stack size:
myStack.push('item1')
Use the pop
method to remove the last item. It returns the removed item or undefined
if the stack was empty:
const item = myStack.pop()
Retrieve the last item using the last
method:
const lastItem = myStack.last()
To watch for changes, utilize the observe
method:
const observer = (item: string | undefined) => {
console.log(`New last item: ${item}`)
}
myStack.observe(observer)
Observers are notified with the new last item and any overloads provided to the push
or pop
methods. This enables more nuanced control and response mechanisms based on stack changes.
You can check the current size of the stack at any time by calling the size
method:
const currentSize = myStack.size()
Both push
and pop
methods accept additional arguments (overloads) that are passed along to observers. This allows for more detailed tracking and reaction to changes in the stack:
myStack.push('newItem', 'additionalInfo')
myStack.pop('contextInfo')
Observers will receive these overloads alongside the stack's latest state, providing rich context for each update.
Here's how you might set up a stack store, add items, remove items, and subscribe to updates:
// Setting up the store
const myStack = createStackStore<string>(['initialItem'])
// Adding an item
myStack.push('anotherItem')
// Observing changes
myStack.observe((item, ...overloads) => {
console.log(`The last item is now: ${item}`, `Overloads:`, overloads)
})
// Removing the last item
const removedItem = myStack.pop()
console.log(`Removed item: ${removedItem}`)
// Checking the size of the stack
console.log(`Current stack size: ${myStack.size()}`)