//Реализовал как-то так. В тепличных условиях ушло минут 40..
/*
Разработайте класс, реализующий буфер текстового редактора. Класс должен предоставлять методы:
1. Добавления строки s в конец буфера
2. Удаления n последних символов из буфера
3. Отмены последней операции
4. Вывода текста всего буфера
5. Вывод последнего символа буфера
*/
class TextEditorBuffer {
#buffer = ''
#operations = []
#OPERATION_TYPES = Object.freeze({
'APPEND': 'APPEND',
'DELETE': 'DELETE'
})
constructor(buffer) {
this.#buffer = buffer
}
//Добавление строки s в конец буфера
append(str) {
this.#buffer += str
this.#operations.push({
type: this.#OPERATION_TYPES.APPEND,
value: str,
})
return this
}
//Удаления n последних символов из буфера
delete(n) {
const value = this.#buffer.slice(this.#buffer.length - n)
this.#buffer = this.#buffer.slice(0, n * -1)
this.#operations.push({
type: this.#OPERATION_TYPES.DELETE,
value,
})
return this.#buffer
}
//Отмена последней операции
undo() {
const operation = this.#operations.pop()
if (operation) {
switch (operation.type) {
case this.#OPERATION_TYPES.DELETE: {
this.#buffer += operation.value
break
}
case this.#OPERATION_TYPES.APPEND: {
this.#buffer = this.#buffer.slice(0, this.#buffer.length - operation.value.length)
break
}
}
}
return this
}
//Вывод текста всего буфера
print(k) {
if (k >= 0) {
return this.#buffer[k - 1]
}
return this.#buffer
}
//Вывод последнего символа буфера
printLast() {
return this.#buffer[this.#buffer.length - 1]
}
}
const textEditorBuffer = new TextEditorBuffer('abcde')
textEditorBuffer.append('fg')
console.log('0', textEditorBuffer.print())
console.log('1', textEditorBuffer.print(6))
textEditorBuffer.delete(5)
console.log('2', textEditorBuffer.print())
textEditorBuffer.undo()
console.log('3', textEditorBuffer.print())
textEditorBuffer.undo()
console.log('4', textEditorBuffer.print())
//А вот это deepseek понаписало.. Я немного.. от этого кода..
class TextBuffer {
constructor() {
this.buffer = []; // Основной буфер для хранения текста
this.history = []; // История операций для отмены
}
// Добавление строки в конец буфера
append(s) {
if (typeof s !== 'string') {
throw new Error('Аргумент должен быть строкой');
}
// Сохраняем текущее состояние буфера в истории
this.history.push([...this.buffer]);
// Добавляем строку в буфер
this.buffer.push(...s.split(''));
}
// Удаление n последних символов из буфера
delete(n) {
if (typeof n !== 'number' || n <= 0) {
throw new Error('Аргумент должен быть положительным числом');
}
// Сохраняем текущее состояние буфера в истории
this.history.push([...this.buffer]);
// Удаляем n последних символов
this.buffer.splice(-n, n);
}
// Отмена последней операции
undo() {
if (this.history.length === 0) {
throw new Error('Нет операций для отмены');
}
// Восстанавливаем предыдущее состояние буфера
this.buffer = this.history.pop();
}
// Вывод текста всего буфера
toString() {
return this.buffer.join('');
}
// Вывод последнего символа буфера
lastChar() {
if (this.buffer.length === 0) {
throw new Error('Буфер пуст');
}
return this.buffer[this.buffer.length - 1];
}
}
// Пример использования
const buffer = new TextBuffer();
buffer.append('Hello');
console.log(buffer.toString()); // "Hello"
buffer.append(' World');
console.log(buffer.toString()); // "Hello World"
buffer.delete(6);
console.log(buffer.toString()); // "Hello"
buffer.undo();
console.log(buffer.toString()); // "Hello World"
console.log(buffer.lastChar()); // "d"