Last active
March 28, 2021 11:42
-
-
Save ChadoNihi/645eace54fc6aec9bf04fcd574abf025 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const COMMAND_PRINT = '3'; | |
const COMMAND_UNDO = '4'; | |
const COMMAND_TO_FUNCTION = { | |
'1': appendToString, | |
'2': deleteLastNLetters, | |
[COMMAND_PRINT]: printNthLetter, | |
[COMMAND_UNDO]: undo | |
}; | |
const WHITESPACE = ' '; | |
function processData(input = '') { | |
const commands = input | |
.split('\n') | |
.slice(1) | |
.map((rawCommand) => parseCommand(rawCommand)); | |
const initialEditorStateHistory = ['']; | |
const editorStateHistory = commands.reduce( | |
(stateHistory, [command, argument]) => reduceToNextEditorState(stateHistory, command, argument), | |
initialEditorStateHistory | |
); | |
} | |
function parseCommand(rawCommand) { | |
return rawCommand | |
.split(WHITESPACE); | |
} | |
function reduceToNextEditorState(stateHistory, command, argument) { | |
const newEditorString = COMMAND_TO_FUNCTION[command](stateHistory, argument); | |
// For performance optimizations, we mutate the state instead of being "pure" and | |
// creating a new array for the state each time. | |
if (command !== COMMAND_PRINT && command !== COMMAND_UNDO) { | |
stateHistory.push(newEditorString); | |
} | |
return stateHistory; | |
} | |
function appendToString(stateHistory, suffix) { | |
return stateHistory[stateHistory.length - 1] + suffix; | |
} | |
function deleteLastNLetters(stateHistory, numOfLettersToDrop) { | |
return stateHistory[stateHistory.length - 1].slice(0, -numOfLettersToDrop); | |
} | |
function printNthLetter(stateHistory, n) { | |
const index = parseInt(n, 10) - 1; | |
const editorString = stateHistory[stateHistory.length - 1]; | |
console.log(editorString[index]); | |
return editorString; | |
} | |
function undo(stateHistory) { | |
return stateHistory.pop(); | |
} | |
process.stdin.resume(); | |
process.stdin.setEncoding('ascii'); | |
_input = ''; | |
process.stdin.on('data', function (input) { | |
_input += input; | |
}); | |
process.stdin.on('end', function () { | |
processData(_input); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment