I been trying to implement a text processor in JavaScript that can handle 4 different types of operations: append, backspace, undo, redo.
The input for this text processor is an array of arraries of a single element or tuples. For example:
const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!']]
textProcessor.process(input)
textProcessor.text // Hey there!
const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!'], ['UNDO'], ['UNDO']]
textProcessor.process(input)
textProcessor.text // Hey
const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!'], ['UNDO'], ['UNDO'], ['REDO'], ['REDO']]
textProcessor.process(input)
textProcessor.text // Hey there!
const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!'], ['BACKSPACE']]
textProcessor.process(input)
textProcessor.text // Hey there
Here is my implementation
class TextProcessor {
constructor() {
this.undos = []
this.redos = []
this.text = ''
this.operations = {
APPEND: (text) => {
this.undos.push(this.text)
this.redos.length = 0
return this.text + text
},
BACKSPACE: () => {
this.undos.push(this.text)
this.redos.length = 0
return this.text.slice(0, -1)
},
UNDO: () => {
const undo = this.undos.pop() ?? ''
this.redos.push(this.text)
return undo
},
REDO: () => {
this.undos.push(this.text)
return this.redos.pop() ?? this.text
},
}
}
process(input) {
input.forEach(([operation, text]) => {
this.text = this.operations[operation](text) ?? this.text
})
}
}
I used an object to map the various operation names to their corresponding functions. Not sure if this is better than switch-case statements.