この解答例はChatGPTによって生成されています,正しいかは自己判断で。

BFE.devでのAI解答例 - JavaScript コーディング問題
13. Stackを使ってQueueを作る

class Queue {
  constructor() {
    this.stack = new Stack();
  }
  enqueue(element) {
    this.stack.push(element);
  }
  peek() {
    let tempStack = new Stack();
    while (this.stack.size() > 0) {
      tempStack.push(this.stack.pop());
    }
    let peekValue = tempStack.peek();
    while (tempStack.size() > 0) {
      this.stack.push(tempStack.pop());
    }
    return peekValue;
  }
  dequeue() {
    let tempStack = new Stack();
    while (this.stack.size() > 0) {
      tempStack.push(this.stack.pop());
    }
    let dequeueValue = tempStack.pop();
    while (tempStack.size() > 0) {
      this.stack.push(tempStack.pop());
    }
    return dequeueValue;
  }
  size() {
    return this.stack.size();
  }
}

// stackクラスを以下のように定義
class Stack {
  constructor() {
    this.stack = [];
  }
  push(item) {
    this.stack.push(item);
  }
  peek() {
    return this.stack[this.stack.length - 1];
  }
  pop() {
    return this.stack.pop();
  }
  size() {
    return this.stack.length;
  }
}

このQueueクラスは、Stackを使って実装されています。enqueue(新しい要素の末尾に追加)、peek(先頭要素を取得)、dequeue(先頭要素を削除して返して、他の要素を前方にシフトします)、size(要素数の取得)の4つのメソッドを提供しています。