All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.unlaxer.sample.calc.CalculatorImpl Maven / Gradle / Ivy

There is a newer version: 1.1.26
Show newest version
package org.unlaxer.sample.calc;

import java.math.BigDecimal;
import java.util.Optional;

import org.unlaxer.Parsed;
import org.unlaxer.StringSource;
import org.unlaxer.Token;
import org.unlaxer.context.ParseContext;
import org.unlaxer.parser.Parser;
import org.unlaxer.sample.calc.parser.FormulaParser;
import org.unlaxer.sample.calc.parser.operator.ExpressionOperator;

public class CalculatorImpl implements Calculator {
	

	@Override
	public CalculateResult calculate(CalculateContext calculateContext, String formula) {
		
		ParseContext parseContext = new ParseContext(new StringSource(formula));
		Parsed parsed = getParser().parse(parseContext);
		try{
			Token rootToken = parsed.getRootToken(true);
			BigDecimal answer = ExpressionOperator.SINGLETON.evaluate(calculateContext,rootToken);
				
			return new CalculateResult(parseContext , parsed, Optional.of(answer));
			
		}catch (Exception e) {
			e.printStackTrace();
			return createResult(e , parseContext , parsed);
		}finally{
			parseContext.close();
		}
	}

	private CalculateResult createResult(Exception e, ParseContext tokenizeContextPointer, Parsed parsed) {
		Errors errors = new Errors(e);
		return new CalculateResult(tokenizeContextPointer , parsed, Optional.empty() , errors);
	}

	@Override
	public Parser getParser() {
		return FormulaParser.SINGLETON;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy