Created
April 26, 2022 01:02
-
-
Save inabajunmr/a12307b1e95433771787503b9a47b98c to your computer and use it in GitHub Desktop.
shunting-yard algorithm1
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
//reference https://qiita.com/phenan/items/df157fef2fea590e3fa9 | |
function shuntingYard1(input: string): string { | |
let i = 0; | |
const stack = ['$']; | |
let output = ''; | |
while (input.length >= i) { | |
const c = input.charAt(i) | |
if (priority(stack[stack.length - 1]) > priority(c)) { | |
output = output + stack.pop(); | |
} else { | |
stack.push(c); | |
i++; | |
} | |
} | |
return output; | |
} | |
function priority(c: string) { | |
switch (c) { | |
case '$': return 0; | |
case '+': return 1; | |
case '*': return 2; | |
default: return 3; | |
} | |
} | |
console.log(shuntingYard1('1+2$')); // 12+ | |
console.log(shuntingYard1('1*2+3$')); // 12*3+ | |
console.log(shuntingYard1('1+2*3$')); // 123*+ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment