<div class="root">
<div class="input">
<label for="in">Enter the Expression: </label>
<input type="text" id="in" name="st">
</div>
<p>(Press Enter After entring the expreesion)</p>
<div class="output"></div>
</div>
.root{
margin-top:40px;
}
label{
font-size:24px;
}
input{
padding:3px 8px;
font-size:18px;
}
p{
margin: 0;
font-sizE:12px;
}
.output{
font-size:18px;
}
$('input').on('keyup', function(e){
if(e.keyCode === 13){
isBalanced(e.target.value);
}
});
const tokens = [ ['{','}'] , ['[',']'] , ['(',')'] ];
function isBalanced(data){
let stack = [];
let bool = true;
let exp = data.split("");
if(exp === null) return printScreen(true);
for(let i=0; i<exp.length; i++){
let val = exp[i]
if(isParenthesis(val)){
if(isOpenParenthesis(val)){
stack.push(val);
}else{
if(stack.length === 0 ){
return printResult(false);
}
let top = stack.pop();
if(!matches(top, val)){
return printResult(false);
}
}
}
}
if(stack.length === 0 ){
return printResult(true);
}else{
return printResult(false);
}
}
function isParenthesis(c){
let str = "{}[]()";
if(str.indexOf(c) < 0){
return false;
}
return true;
}
function isOpenParenthesis(c){
let str = "{[(";
if(str.indexOf(c) < 0){
return false;
}
return true;
}
function matches(top, current){
let bool = false;
tokens.some(function(token, i){
if(token[0] === top){
if(token[1] === current){
bool= true;
}else{
bool= false;
}
}
});
return bool;
}
function printResult(bool){
let el = $('.output');
if(bool){
el.html('<h2>Woohooo!</h2> The Parenthesis are Balanced.');
}else{
el.html('<h2>Ack!</h2> The Parenthesis are Not Balanced.');
}
}
This Pen doesn't use any external CSS resources.