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

org.unlaxer.tinyexpression.Calculator Maven / Gradle / Ivy

package org.unlaxer.tinyexpression;

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

import org.unlaxer.Parsed;
import org.unlaxer.StringSource;
import org.unlaxer.Token;
import org.unlaxer.context.ParseContext;
import org.unlaxer.parser.Parser;

public interface Calculator {
	
	public default CalculateResult calculate(CalculationContext calculateContext, String formula) {
		ParseContext parseContext = new ParseContext(new StringSource(formula));
		Parsed parsed = getParser().parse(parseContext);
		try{
			Token rootToken = tokenReduer().apply(parsed.getRootToken(true));
			T answer = getCalculatorOperator().evaluate(calculateContext,rootToken);
				
			return new CalculateResult(parseContext , parsed, Optional.of(toBigDecimal(answer)));
			
		}catch (Exception e) {
			Errors errors = new Errors(e);
			return new CalculateResult(parseContext , parsed, Optional.empty() , errors);
		}finally{
			parseContext.close();
		}
	}
	
	public Parser getParser();
	
	public TokenBaseOperator getCalculatorOperator();
	
	public BigDecimal toBigDecimal(T value);
	
	public float toFloat(T value);
	
	public default UnaryOperator tokenReduer(){
		return UnaryOperator.identity();
	}

	
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy