FORTH 表达式计算 js版(加减乘除运算)

2017-10-20  本文已影响14人  26d1e4f85623

FORTH语言是一个很早很早就出现的语言。

在FORTH中,加法计算是这样的:

 1 1 +

再复杂一点可以是这样:

1 1 + 2 * 4 +

下面就这个计算流程实现JS版加减乘除:


class Forth {
    constructor() {
        this.stack = [];
        this.ops = ['+', '-', '*', '/'];
    }

    push(n) {
        if (this.isOper(n)) {
            let len = this.stack.length;
            let v = this.exec(this.stack, n);
            this.stack.splice(0, len, v);
            return;
        }
        if (isNaN(n)) {
            throw  new Error('unknown word: ' + n);
        }
        this.stack.push(Number(n));
        console.log('stack', this.stack)
    }

    isOper(n) {
        return this.ops.includes(n);
    }

    exec(arrs, operator) {
        if (!operator) {
            return arrs[arrs.length - 1];
        }
        return eval(arrs[0] + operator + arrs[1]);
    }

    input(expression) {
        let me = this;
        let exp = expression.trim().split(/\s+/);
        exp.forEach((item, index) => {
            me.push(item);
            if (index === exp.length - 1) {
                let v = me.exec(me.stack);
                console.log(v);
            }
        });
    }

}

使用case:

var f = new Forth();
f.input('1 1 + 1 + 5 * 2 +');  //17
上一篇下一篇

猜你喜欢

热点阅读