LoginSignup
2
2

More than 5 years have passed since last update.

javascript で四則演算数式を評価する例

Last updated at Posted at 2013-03-20

javascript でのパーサージェネレーター pegjs をつかって数式評価をしてみました。
(google 検索で数式を指定したときに現れる電卓の様なものを作る場合、このような数式パーサーが必要になりますね)

デモ:http://homepage2.nifty.com/youichi_kato/src/pegjs/expression/calc_01.html

pegjs のソース: http://homepage2.nifty.com/youichi_kato/src/pegjs/expression/arithmetics.pegjs
gist 上のソース: https://gist.github.com/katoy/5201247

このコードは演算子の右結合、左結合の例を含んでいます。
"*", "/" は左結合、 "^" は右結合としています。

pegjs での左結合の実装については以下を参考にしました。
https://groups.google.com/forum/?fromgroups=#!topic/pegjs/shpo7POBHuE

....
When fed this equation: 1/2*3
Returns: 0.166666666...
When it should return: 1.5
Because it is essentially being parsed as 1/(2*3)
How can I change this grammar around to parse from left to right?
...

2
2
3

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
2
2