Skip to content
This repository has been archived by the owner on Mar 19, 2021. It is now read-only.

Commit

Permalink
Add result history with @ symbol
Browse files Browse the repository at this point in the history
  • Loading branch information
alfredxing committed Mar 1, 2015
1 parent 252e9a0 commit 7ac72fa
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions compute/compute.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,33 @@ import (
"github.com/alfredxing/calc/operators/functions"
)

var resHistory = []float64{}

func Evaluate(in string) (float64, error) {
floats := NewFloatStack()
ops := NewStringStack()
s := initScanner(in)

var prev token.Token = token.ILLEGAL
var back int = -1

ScanLoop:
for {
_, tok, lit := s.Scan()

if lit != "@" && back > -1 {
floats.Push(getHistory(back))
if prev == token.RPAREN || constants.IsConstant(prev.String()) {
evalUnprecedenced("*", ops, floats)
}
back = -1
}

switch {
case tok == token.EOF:
break ScanLoop
case lit == "@":
back += 1
case constants.IsConstant(lit):
floats.Push(constants.GetValue(lit))
if prev == token.RPAREN || isOperand(prev) {
Expand Down Expand Up @@ -99,6 +113,7 @@ ScanLoop:
if err != nil {
return 0, errors.New("Expression could not be parsed!")
}
pushHistory(res)
return res, nil
}

Expand Down Expand Up @@ -169,6 +184,14 @@ func parseOperator(lit string) *operators.Operator {
return operators.FindOperatorFromString(lit)
}

func getHistory(back int) float64 {
return resHistory[back]
}

func pushHistory(res float64) {
resHistory = append([]float64{res}, resHistory...)
}

func initScanner(in string) scanner.Scanner {
var s scanner.Scanner
src := []byte(in)
Expand Down

0 comments on commit 7ac72fa

Please sign in to comment.