Skip to content

Commit c9f5245

Browse files
committed
postfix with functions
1 parent 5919ff7 commit c9f5245

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

app.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const calc = require('./calc')
33

44
module.exports = function app (exp) {
55
var type = postfixer.getExpressionType(exp)
6+
console.log(type)
67
var rst = null
78
if (type === postfixer.PREFIX) {
89
rst = calcPrefix(exp)
@@ -58,6 +59,16 @@ function calcPostfix (exp) {
5859
var o1 = getValue(stack.pop())
5960
var rst = calc(token, o1, o2)
6061
stack.push(rst)
62+
} else if (token[token.length - 1] === '(') {
63+
var args = []
64+
var o = stack.pop()
65+
while (o !== ')') {
66+
args.push(o)
67+
o = stack.pop()
68+
}
69+
args.reverse()
70+
var rst = Math[token.substr(0, token.length - 1)].apply(null, args)
71+
stack.push(rst)
6172
} else {
6273
stack.push(token)
6374
}

postfixer.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const MATH_EXTEND = {
1717
const isOperator = require('./calc').isOperator
1818

1919
function getExpressionType (exp) {
20-
if (isOperator(exp[exp.length - 1])) return POSTFIX
20+
if (isOperator(exp[exp.length - 1]) || exp[exp.length - 1] === '(') return POSTFIX
2121
if (isOperator(exp[0])) {
2222
// negative number -> infix notation
2323
if (exp.length > 1 && exp[1] >= '0' && exp[1] <= '9') return INFIX

test/z.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const test = require('tape')
2+
var app = require('../app')
3+
4+
test('func - postfix test', function (t) {
5+
t.equal(app('1 3 +'), 4)
6+
7+
t.equal(app(') 3 0 -2 19 min('), 4)
8+
9+
t.equal(app(') 3 0 -2 19 max('), 4)
10+
11+
t.equal(app(') -1 abs( 10 +'), 4)
12+
13+
t.equal(app(') 2 ) 2 3 pow( - max('), 4)
14+
15+
t.end()
16+
})

0 commit comments

Comments
 (0)