Created
April 12, 2022 08:54
-
-
Save kevinmmartins/7c16700bd948ee5c67da19fcc6c3e874 to your computer and use it in GitHub Desktop.
codility task
This file contains 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 MAX_VALUE = 1048575 | |
const integerOperation = (integer) => (stack) => { | |
stack.push(parseInt(integer)) | |
} | |
const popOperation = (stack) => { | |
stack.pop() | |
} | |
const dupOperation = (stack) => { | |
if(stack.length < 0) { | |
throw new Error('Invalid values') | |
} | |
const lastElement = stack.slice(-1)[0] | |
integerOperation(lastElement)(stack) | |
} | |
const addOperation = (stack) => { | |
if(stack.length <= 1){ | |
throw new Error('Invalid values') | |
} | |
const add = stack.slice(-2).reduce((a,b) => (a +b )) | |
if(add > MAX_VALUE){ | |
throw new Error('Max value limit') | |
} | |
stack.splice(-2, 2) | |
integerOperation(add)(stack) | |
} | |
const subtractOperation = (stack) => { | |
if(stack.length <= 1) { | |
throw new Error('Invalid values') | |
} | |
const subtract = stack.slice(-2).reduce((a, b) => (b - a)) | |
if(subtract < 0){ | |
throw new Error('Negative result from subtract') | |
} | |
stack.splice(-2, 2) | |
integerOperation(subtract)(stack) | |
} | |
const operationsMap = { | |
"+" : addOperation, | |
"-" : subtractOperation, | |
"DUP": dupOperation, | |
"POP" : popOperation | |
} | |
const getOperation = value => { | |
const operation = operationsMap[value] | |
return operation ? operation : integerOperation(value) | |
} | |
function solution(S = "") { | |
const stackResult = [] | |
const operationsCommands = S.split(" ") | |
try{ | |
operationsCommands.forEach((command) => { | |
const operationFunction = getOperation(command) | |
operationFunction(stackResult) | |
}) | |
return stackResult.pop() | |
} | |
catch (error) { | |
return -1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment