Stack implementation missing length property! (found 2nd bug in Absolute Beginner’s Guide to Algorithms)

Dear author,
I hope this message finds you well. I am writing to bring to your attention a potential issue with the Stack implementation provided in your Chapter 19 DFS example (stack_v1.js).

It appears that the Stack class lacks an implementation for the length property, which results in an unexpected behavior in the DFS implementation provided in Chapter 19. Specifically, the condition while (discovered.length > 0) does not work as intended due to the absence of the length property.

To address this issue, I suggest adding the following length method to the Stack class:

class Stack {
  constructor(...items) {
    this.items = items;
  }
  
  // ... (other methods remain unchanged)

  get length() {
    return this.items.length;
  }
}

This modification ensures that the DFS algorithm correctly checks for an empty stack.

Best regards

Thanks for being thorough! I had this change queued but it somehow failed to get updated on the server. Here is the correct version: https://www.kirupa.com/js/stack_v1.js?new (I added the ?new to bypass the CDN caching!)

Below is the full implementation for easy reference:

/**
 * A simple Stack implementation in JavaScript
 * 
 * Visit https://www.kirupa.com for a deep-dive on how this works!
 * 
 * Copyright 2023 Kirupa Chinnathambi (@kirupa)
 * License: MIT
 */
class Stack {
  constructor(...items) {
    // Initialize the stack with any pre-populated items.
    this.items = items;
  }

  clear() {
    // Set the length of the items array to 0 to effectively clear the stack.
    this.items.length = 0;
  }

  clone() {
    // Use the spread operator to create a new stack with a copy of the current items.
    return new Stack(...this.items);
  }

  contains(item) {
    // Check if the item exists in the stack using `includes`.
    return this.items.includes(item);
  }

  peek() {
    // Get the last item in the stack without removing it (LIFO principle).
    return this.items[this.items.length - 1];
  }

  pop() {
    // Remove and return the last item from the stack (LIFO principle).
    return this.items.pop();
  }

  push(item) {
    // Add an item to the top of the stack.
    this.items.push(item);
    return item;
  }

  get length() {
    // Return the current size of the stack (number of items).
    return this.items.length;
  }
}