Basic stack operations (Push, Pop)

Implement a simple stack data structure for Bitcoin script operations.

Task

Complete the Stack class in challenges/Stack.js:

  1. push(hexValue): Add a new item (converted from hex to Buffer) to the stack.
  2. pop(): Remove and return the top item from the stack.

Both methods should return a new Stack instance.

Implementation

P2PK ScriptPubKey Decoder Exercise
export class Stack {
    constructor(items = []) {
        this.items = items;
    }

    push(hexValue) {
        // TODO: Implement push method
    }

    pop() {
        // TODO: Implement pop method
    }

    getItems() {
        return this.items;
    }

}

Ready to Code?

Choose your preferred language to begin

Hints

Click to reveal next hint (0/4)
  • Use Buffer.from(hexValue, 'hex') to convert hex strings to Buffers
  • Create new arrays with spread operator [...this.items] for immutability
  • Return new Stack instances in both push and pop methods
  • Check for empty stack in pop method and throw an error if empty

Solution

Solution Code

Test your implementation using the Stack Simulator above.