@@ -17,8 +17,6 @@ actual class JavaScriptEngine actual constructor() {
1717 private val json: Json = Json .Default
1818 private val jsContext: ContextProviderDynamic = ContextProviderDynamic ()
1919
20- private var contextObjects: Map <String , JsType > = emptyMap()
21-
2220 @Volatile
2321 var isClosed = false
2422 private set
@@ -37,7 +35,13 @@ actual class JavaScriptEngine actual constructor() {
3735 }
3836
3937 actual fun setContextObjects (vararg context : Pair <String , JsType >) {
40- this .contextObjects = mapOf (* context)
38+ val scriptContext: Map <String , JsType > = context.toMap()
39+ jsContext.context = scriptContext
40+
41+ val scriptWithContext: String = buildString {
42+ fillContext(scriptContext)
43+ }
44+ quickJs.evaluate(scriptWithContext)
4145 }
4246
4347 actual fun evaluate (context : Map <String , JsType >, script : String ): JsType {
@@ -60,38 +64,35 @@ actual class JavaScriptEngine actual constructor() {
6064 context : Map <String , JsType >,
6165 script : String
6266 ): JsType {
63- val scriptContext: Map <String , JsType > = contextObjects + context
6467 jsContext.activeScript = script
65- jsContext.context = scriptContext
68+ jsContext.context = context
6669
6770 val scriptWithContext: String = buildString {
68- scriptContext.forEach { (name, jsType) ->
69-
70- try {
71- quickJs.evaluate(" $name ;" )
72- return @forEach
73- } catch (e: Throwable ) { }
74-
75- append(" const " )
76- append(name)
77- append(" = " )
78- append(
79- when (jsType) {
80- is JsType .Bool -> " mokoJsContext.getBool('$name ')"
81- is JsType .DoubleNum -> " mokoJsContext.getDouble('$name ')"
82- is JsType .Json -> " JSON.parse(mokoJsContext.getString('$name '))"
83- JsType .Null -> " null"
84- is JsType .Str -> " mokoJsContext.getString('$name ')"
85- }
86- )
87- append(" ;\n " )
88- }
71+ fillContext(context)
8972 append(" mokoJavaScriptProcessResult(eval(mokoJsContext.getScript()));" )
9073 }
9174 val result: Any? = quickJs.evaluate(scriptWithContext)
9275 return handleQuickJsResult(result)
9376 }
9477
78+ private fun StringBuilder.fillContext (context : Map <String , JsType >) {
79+ context.forEach { (name, jsType) ->
80+ append(" const " )
81+ append(name)
82+ append(" = " )
83+ append(
84+ when (jsType) {
85+ is JsType .Bool -> " mokoJsContext.getBool('$name ')"
86+ is JsType .DoubleNum -> " mokoJsContext.getDouble('$name ')"
87+ is JsType .Json -> " JSON.parse(mokoJsContext.getString('$name '))"
88+ JsType .Null -> " null"
89+ is JsType .Str -> " mokoJsContext.getString('$name ')"
90+ }
91+ )
92+ append(" ;\n " )
93+ }
94+ }
95+
9596 private fun handleQuickJsResult (result : Any? ): JsType {
9697 return when (result) {
9798 null -> JsType .Null
0 commit comments