Created
August 27, 2019 03:14
-
-
Save marvinsjsu/4b72c128650fe0f84e8acace0583db22 to your computer and use it in GitHub Desktop.
Evaluating circuits
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
function circuitsOutput(circuitsExpression) { | |
// Write your code here | |
let output = []; | |
let opStack = []; | |
let values = []; | |
let currEl; | |
let frame; | |
let frameOutput = null; | |
let bracketValues = []; | |
let operand, currFrame; | |
function parse(exprRecur) { | |
if (exprRecur.length === 0){ | |
// console.log('returning frameOutput: ', frameOutput, opStack); | |
return frameOutput; | |
}; | |
currEl = exprRecur.shift(); | |
switch(currEl) { | |
case '[': | |
currEl = exprRecur.shift(); | |
frame = new Frame(currEl); | |
opStack.push(frame); | |
break; | |
case ']': | |
frame = opStack.pop(); | |
frameOutput = frame.evaluate(); | |
if (opStack.length > 0) { | |
frame = opStack[opStack.length - 1]; | |
frame.addArg(frameOutput); | |
} else { | |
// console.log('returning frameOutput: ', frameOutput); | |
return frameOutput; | |
} | |
break; | |
case '1': | |
frame.addArg(true); | |
break; | |
case '0': | |
frame.addArg(false); | |
break; | |
} | |
// console.log(opStack); | |
// debugger; | |
parse(exprRecur); | |
} | |
let expr; | |
circuitsExpression.forEach((str) => { | |
expr = str.split(''); | |
parse(expr); | |
output.push(frameOutput ? 1 : 0); | |
}); | |
return output; | |
} | |
function Frame(operation) { | |
this.operation = operation; | |
this.func = null; | |
this.args = []; | |
return { | |
func: this.func, | |
args: this.args, | |
addArg: (val) => { | |
this.args.push(val); | |
}, | |
evaluate: () => { | |
// console.log('evaluate - args:', this.args, this.operation); | |
if (this.operation === '|') { | |
return this.args.includes(true); | |
} else if (this.operation === '&') { | |
return this.args.includes(false) ? false : true; | |
} else if (this.operation === '!') { | |
return !this.args[0]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment