계산기 (3)


<!doctype html>
<html>
<body>
<script>
var expression = prompt('계산식을 입력해 주세요');
var cursor = 0;
var lastCursorPosition = 0;
var tokens = [];

function supportOperator(op){
return(op == '+' || op == '-')
}

function isOperator(value){
return supportOperator(value);
}
while(cursor < expression.length){
if(isOperator(expression[cursor])){
tokens.push(Number(expression.slice(lastCursorPosition, cursor)));
tokens.push(expression[cursor]);

lastCursorPosition = cursor + 1;
}
cursor = cursor + 1;
}
tokens.push(Number(expression.slice(lastCursorPosition, cursor)));
tokens.push('+'); // Fake operator

var index = 0;
var sum = 0;
var operator = '+';

while(index < tokens.length){
if(isOperator(tokens[index])){
if(operator != ''){
if(operator == '+'){
sum = sum + tokens[index-1];
}else {
sum = sum - tokens[index-1];
}
}
operator = tokens[index];
}
index = index + 1;
}
console.log(sum);
</script>
</body>
</html>


'javascript' 카테고리의 다른 글

문제와 답 프로그램  (0) 2017.09.04
계산기 (4)  (0) 2017.09.04
계산기 (2)  (0) 2017.09.04
계산기  (0) 2017.09.04
천 단위 쉼표 표시  (0) 2017.09.04

+ Recent posts