この解答例はChatGPTによって生成されています,正しいかは自己判断で。
BFE.devでのAI解答例 - JavaScript コーディング問題
59. browser historyを作る
class BrowserHistory {
constructor() {
this.history = [];
this.currentIdx = -1;
}
visit(url) {
// 新しいアドレスに移動したら、現在位置より後ろの履歴を削除する
this.history.splice(this.currentIdx + 1);
// 新しいアドレスを追加する
this.history.push(url);
// 現在位置を新しいアドレスのインデックスにする
this.currentIdx = this.history.length - 1;
}
goBack() {
if (this.currentIdx > 0) {
// 現在位置を前にずらす
this.currentIdx--;
return this.history[this.currentIdx];
} else {
// もう前に戻れない場合は現在のアドレスを返す
return this.history[this.currentIdx];
}
}
forward() {
if (this.currentIdx < this.history.length - 1) {
// 現在位置を後ろにずらす
this.currentIdx++;
return this.history[this.currentIdx];
} else {
// もう進めない場合は現在のアドレスを返す
return this.history[this.currentIdx];
}
}
}