Skip to content

Commit 8a8de51

Browse files
committed
feat: make Function constructor
1 parent 099201e commit 8a8de51

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

‎src/java/me/topchetoeu/jscript/lib/FunctionLib.java‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
11
package me.topchetoeu.jscript.lib;
22

3+
import me.topchetoeu.jscript.common.Filename;
4+
import me.topchetoeu.jscript.runtime.Compiler;
5+
import me.topchetoeu.jscript.runtime.Context;
6+
import me.topchetoeu.jscript.runtime.scope.ValueVariable;
37
import me.topchetoeu.jscript.runtime.values.ArrayValue;
48
import me.topchetoeu.jscript.runtime.values.CodeFunction;
59
import me.topchetoeu.jscript.runtime.values.FunctionValue;
610
import me.topchetoeu.jscript.runtime.values.NativeFunction;
11+
import me.topchetoeu.jscript.runtime.values.Values;
712
import me.topchetoeu.jscript.utils.interop.Arguments;
813
import me.topchetoeu.jscript.utils.interop.Expose;
14+
import me.topchetoeu.jscript.utils.interop.ExposeConstructor;
915
import me.topchetoeu.jscript.utils.interop.ExposeTarget;
1016
import me.topchetoeu.jscript.utils.interop.WrapperName;
1117

1218
@WrapperName("Function")
1319
public class FunctionLib {
20+
private static int i;
21+
1422
@Expose public static Object __apply(Arguments args) {
1523
return args.self(FunctionValue.class).call(args.ctx, args.get(0), args.convert(1, ArrayValue.class).toArray());
1624
}
@@ -51,4 +59,25 @@ public static FunctionValue __asyncGenerator(Arguments args) {
5159
public static FunctionValue __generator(Arguments args) {
5260
return new GeneratorFunctionLib(args.convert(0, CodeFunction.class));
5361
}
62+
63+
@ExposeConstructor
64+
public static Object __constructor(Arguments args) {
65+
var compiler = Compiler.get(args);
66+
67+
var parts = args.convert(String.class);
68+
if (parts.length == 0) parts = new String[] { "" };
69+
70+
var src = "return function(";
71+
72+
for (var i = 0; i < parts.length - 1; i++) {
73+
if (i != 0) src += ",";
74+
src += parts[i];
75+
}
76+
77+
src += "){" + parts[parts.length - 1] + "}";
78+
79+
var body = compiler.compile(new Filename("jscript", "func/" + i++), src);
80+
var func = new CodeFunction(Context.clean(args.ctx), "", body, new ValueVariable[0]);
81+
return Values.call(args, func, null);
82+
}
5483
}

0 commit comments

Comments
 (0)