Dave Jarvis' Repositories

git clone https://repo.autonoma.ca/repo/keenwrite.git

Cache results from R expressions

AuthorDaveJarvis <email>
Date2020-06-17 17:19:20 GMT-0700
Commit0f11b87792115e9f43e4b9cb8038b55f3a24781f
Parentd568ebf
Delta21 lines added, 5 lines removed, 16-line increase
src/main/java/com/scrivenvar/processors/InlineRProcessor.java
import com.scrivenvar.service.Options;
import com.scrivenvar.service.events.Notifier;
-import org.renjin.eval.EvalException;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.nio.file.Path;
+import java.util.HashMap;
import java.util.Map;
private static final Options OPTIONS = Services.load( Options.class );
- // Only one editor is open at a time.
+ /**
+ * Only one editor is open at a time.
+ */
private static final ScriptEngine ENGINE =
(new ScriptEngineManager()).getEngineByName( "Renjin" );
+
+ /**
+ * Where to put document inline evaluated R expressions.
+ */
+ private final Map<String, Object> mEvalCache = new HashMap<>();
/**
// Pass the R statement into the R engine for evaluation.
try {
- final Object result = eval( r );
+ final Object result = evalText( r );
// Append the string representation of the result into the text.
* @return The object resulting from the evaluation.
*/
- private Object eval( final String r ) throws ScriptException, EvalException {
- return getScriptEngine().eval( r );
+ private Object evalText( final String r ) {
+ return mEvalCache.computeIfAbsent( r, v -> eval( r ) );
+ }
+
+ private Object eval( final String r ) {
+ try {
+ return getScriptEngine().eval( r );
+ } catch( final ScriptException e ) {
+ getNotifier().notify( e );
+ return "";
+ }
}