LoginSignup
0

More than 5 years have passed since last update.

Vue.js で逆ポーランド電卓のスタックを見る

Last updated at Posted at 2018-11-10

2 * 3 + 4 * 5 という数式は人間には一目でもコンピュータには難しいのでいったん 2 3 * 4 5 * + という並びにしてから実行します。

Ruby でもこんな風にすると並びが変わっているのが確認できます。

puts RubyVM::InstructionSequence.compile("2 * 3 + 4 * 5").disassemble
# >> == disasm: #<ISeq:<compiled>@<compiled>:1 (1,0)-(1,13)>=================
# >> 0000 putobject        2                                               (   1)[Li]
# >> 0002 putobject        3
# >> 0004 opt_mult         <callinfo!mid:*, argc:1, ARGS_SIMPLE>, <callcache>
# >> 0007 putobject        4
# >> 0009 putobject        5
# >> 0011 opt_mult         <callinfo!mid:*, argc:1, ARGS_SIMPLE>, <callcache>
# >> 0014 opt_plus         <callinfo!mid:+, argc:1, ARGS_SIMPLE>, <callcache>
# >> 0017 leave            

で、その並びの実行を試せるようにしたのがこれです。

See the Pen RPN by Akira Ikeda (@akicho8) on CodePen.

2 3 * 4 5 * + の順に入力していくとどのようにスタックが変化していっているかがわかります。

コードの内容

pug
#app
  input(v-model.trim="str" @keyup="run")
  input(v-for="e in [...stack].reverse()" :value="e" readonly)
js
new Vue({
  el: "#app",
  data: {
    str: "",
    stack: [],
  },
  methods: {
    run() {
      if (this.str !== "") {
        if (/\d+/.test(this.str)) {
          this.stack.push(this.str)
        } else {
          const left = this.stack.pop()
          const right = this.stack.pop()
          this.stack.push(eval(`${left}${this.str}${right}`))
        }
        this.str = ""
      }
    },
  },
})

数字なら push してそうじゃないなら2つ取り出して演算して push します。
かなり手抜きです。
@keyup のところを @keyup.enter にすると2桁以上の実行ができます。

おわり

結局何の記事かよくわからなくなってしまいましたが、HTMLの部分も含めて Vue.js だとこんなのが書きやすいです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0