A typescript implementation of Circular Stack.
-
npm
npm install --save @algorithm.ts/stack
-
yarn
yarn add @algorithm.ts/stack
Circular stack is a stack structure, the main purpose of its design is to reuse space as much as possible on the basis of ordinary stacks. Circular stacks usually need to specify a capacity, if the number of elements in the stack exceeds the capacity, only the most recent capacity elements are kept in the stack. Other operations are the same as ordinary stacks.
-
ICircularStack: CircularStack implements the ICircularStack interface.Signature Description readonly capacity: numberThe capacity of stack, which also means the max elements of the stack. readonly size: numberThe count of the elements in the stack. at(index: number): T | undefinedGet the element at the given index. clear(): voidClear the stack. consuming(): IterableIterator<T>Popup the elements from the stack one by one. count(filter: (element: T, index: number) => boolean): numberCount the elements in the stack which matched by the filter. pop(newElement?: T): T | undefinedPopup the top element, and push the given newElementif it is notundefined.push(element: T): thisPush a element into the stack. rearrange(filter: (element: T, index: number) => boolean): voidOnly preserve the elements matched the filter. resize(capacity: number): voidResize the capacity of stack with the given size. top(): T|undefinedGet the top element from the stack. update(index: number, element: T): voidChange the element at the given index. -
ICircularStackPropsexport interface ICircularStackProps { /** * Initial capacity of the circular stack. */ capacity?: number }
-
Basic -- CircularStack
import { CircularStack } from '@algorithm.ts/stack' const stack = new CircularStack<{ name: string }>({ capacity: 100 }) // Append a element to the end of the stack. stack.push({ name: 'alice' }) // => 0 stack.push({ name: 'bob' }) // => 1 stack.size // => 2 // Get the front element of the stack. stack.top() // => { name: 'bob' } // Take off the first element of the stack. stack.pop() // => { name: 'bob' } stack.size // => 1