Created
June 12, 2017 18:15
-
-
Save BeKnowDo/37a43c7a1dcae322bbdbb6aa10cd64eb to your computer and use it in GitHub Desktop.
Wordmachine
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 wordMachine = (commands) => { | |
| const operations = commands.split(' '); | |
| let stack = []; | |
| commandCount = 0; | |
| operations.map((item, index) => { | |
| let detectInteger = parseInt(item); | |
| commandCount++; | |
| //console.log(stack); | |
| if (Number.isInteger(detectInteger)) { | |
| stack.push(detectInteger); | |
| } else { | |
| switch (item) { | |
| case 'DUP': | |
| //console.log(`Duplicated ${stack[stack.length - 1]}`); | |
| return stack.push(stack[stack.length - 1]); | |
| case 'POP': | |
| //console.log(`Popped ${stack[stack.length - 1]}`); | |
| return stack.pop(); | |
| case '+': | |
| let addedIntegers = stack[stack.length - 1] + stack[stack.length - 2]; | |
| stack.pop(); | |
| stack.pop(); | |
| return stack.push(addedIntegers); | |
| case '-': | |
| let subtractedIntegers = stack[stack.length - 1] - stack[stack.length - 2]; | |
| stack.pop(); | |
| stack.pop(); | |
| return stack.push(subtractedIntegers); | |
| } | |
| } | |
| }); | |
| console.log(commandCount); | |
| if(isNaN(stack[stack.length - 1]) === true) { | |
| return -1; | |
| } else { | |
| return stack[stack.length - 1]; | |
| } | |
| } | |
| console.clear(); | |
| //const test = wordMachine('13 DUP 4 POP 5 DUP + DUP + -'); | |
| const test = wordMachine('5 6 + -'); | |
| console.log(test); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment