Skip to content

Instantly share code, notes, and snippets.

@inabajunmr
Created April 26, 2022 01:02
Show Gist options
  • Save inabajunmr/a12307b1e95433771787503b9a47b98c to your computer and use it in GitHub Desktop.
Save inabajunmr/a12307b1e95433771787503b9a47b98c to your computer and use it in GitHub Desktop.
shunting-yard algorithm1
//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