aboutsummaryrefslogtreecommitdiffstats
path: root/calculator.go
blob: 30cc7ec8db6a3510595eb495a71b59494817e2ce (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import "strconv"

type Stack []float64

type Calculator struct {
	stack  Stack
	buffer string
}

// add performs addition when the user inputs the '+' operator.
func (c *Calculator) add() {
	if len(c.stack) < 1 {
		return
	}
	if con := parseConstant(c.buffer); con != nil {
		c.stack[len(c.stack)-1] += *con
	} else if f, err := strconv.ParseFloat(c.buffer, 64); err == nil {
		c.stack[len(c.stack)-1] += f
	} else if len(c.stack) > 1 {
		c.stack[len(c.stack)-2] += c.stack[len(c.stack)-1]
		c.stack = c.stack[:len(c.stack)-1]
	}
	c.buffer = ""
}