Snowcone field notes 02 / 03

A JavaScript stack with Snowcone: push, pop, and peek

For a LIFO stack in Node.js, Snowcone provides Stack with push(), pop(), peek(), size, and isEmpty(). The last item pushed is the first item popped. It is a small wrapper around a private JavaScript array, with an API that expresses stack operations directly.

Package note: This guide describes version 0.2.0 and includes native alternatives where they are useful.

Install and try a LIFO stack

Use Node.js 20 or later and ECMAScript modules. Save the examples as .mjs files, or set "type": "module" in your project’s package.json.

npm install [email protected]

Pinning the version makes these examples reproducible. Check npm for newer releases and compare their API before upgrading.

import { Stack } from "snowcone";

const stack = new Stack();
stack.push("first page");
stack.push("second page");

console.log(stack.peek());    // second page
console.log(stack.pop());     // second page
console.log(stack.size);      // 1
console.log(stack.pop());     // first page
console.log(stack.isEmpty()); // true
console.log(stack.pop());     // undefined

LIFO means last in, first out. In this example, second page is on top. Both peek() and pop() return undefined on an empty stack, but only pop() removes an item when one exists.

Why choose an explicit stack?

Stacks fit problems where you need to revisit the most recent unfinished item: matching brackets, iterative depth-first traversal, parsing, or managing an undo history. A stack stores the order; your application still defines what an item means and how to act on it.

Snowcone keeps its backing array private and exposes the handful of operations a stack needs. That can make intent clearer than passing around a general-purpose array. It does not introduce a fundamentally different storage strategy from using an array’s end directly.

Example: match nested brackets

Every opening bracket becomes unfinished work on the stack. A closing bracket must match the most recent opening bracket. At the end, no unmatched opening bracket should remain.

import { Stack } from "snowcone";

function hasBalancedBrackets(text) {
  const stack = new Stack();
  const matching = new Map([
    [")", "("],
    ["]", "["],
    ["}", "{"]
  ]);

  for (const char of text) {
    if ("([{".includes(char)) {
      stack.push(char);
    } else if (matching.has(char)) {
      if (stack.isEmpty() || stack.pop() !== matching.get(char)) {
        return false;
      }
    }
  }

  return stack.isEmpty();
}

console.log(hasBalancedBrackets("a + (b * [c])")); // true
console.log(hasBalancedBrackets("([)]"));          // false

This scans the text once, giving O(n) time under the ordinary array cost model and O(n) worst-case extra space for deeply nested input. It checks bracket characters only; it is not a JavaScript parser and does not account for brackets inside strings or comments.

Stack API and behavior

MemberBehavior
push(item)Put an item on top; returns undefined.
pop()Remove and return the top item, or undefined if empty.
peek()Return the top item without removing it, or undefined if empty.
sizeRead the current item count; use stack.size.
isEmpty()Return whether the stack has no items.

With the usual dynamic-array model, pushes are amortized O(1), while peeks, size checks, and end removals are O(1). Storage is O(n) in the number of stored items. These are implementation-level expectations, not engine-independent latency guarantees.

When a native array is enough

JavaScript arrays already provide push() and pop(). If you only need a local stack in a short function, this may be all you need:

const stack = [];
stack.push("first");
stack.push("second");
console.log(stack.at(-1)); // second: inspect the top
console.log(stack.pop()); // second: remove the top
console.log(stack.length); // 1

Choose Snowcone for an explicit stack interface or consistency with its Queue API. Choose an array when reducing dependencies matters more than that wrapper. Note one difference: native Array.push() returns the new length, while Stack.push() in Snowcone 0.2.0 returns undefined.

Limits to know before using it

A Snowcone stack is a synchronous in-memory container. It is not the engine’s function-call stack, and it does not make recursion deeper or provide persistence. Objects are stored by reference; pushing one does not clone it.

Start with new Stack() and push initial items yourself. There is no public iterator or built-in maximum capacity. A stored undefined looks like an empty return value, so check isEmpty() if that distinction matters. Use Node.js for these root-import examples: the published entry point also imports the Node-only readLines helper.

Common questions

Does peek remove the top item?

No. Use peek() to inspect and pop() to remove.

Is Stack the same as Queue?

No. Stack removes the newest item first; Queue removes the oldest. Choose based on the order your algorithm requires.

Is a Stack object faster than an array?

This implementation uses an array internally, and this guide makes no speedup claim. Its benefit is the focused interface.

Sources and version

Examples were checked against the published [email protected] package. Implementation details refer to the linked source snapshot, not a promise about future versions.