Ver Fonte

Merge pull request #3209 from nadako/1997_array_push_closure

[js] create proper closure for Array.push (closes #1997)
Dan Korostelev há 11 anos atrás
pai
commit
7ca1b27a65
2 ficheiros alterados com 24 adições e 0 exclusões
  1. 12 0
      genjs.ml
  2. 12 0
      tests/unit/issues/Issue1997.hx

+ 12 - 0
genjs.ml

@@ -492,6 +492,12 @@ and gen_expr ctx e =
 		print ctx "$iterator(";
 		gen_value ctx x;
 		print ctx ")";
+	| TField (x,FClosure (Some {cl_path=[],"Array"}, {cf_name="push"})) ->
+		(* see https://github.com/HaxeFoundation/haxe/issues/1997 *)
+		add_feature ctx "use.$arrayPushClosure";
+		print ctx "$arrayPushClosure(";
+		gen_value ctx x;
+		print ctx ")"
 	| TField (x,FClosure (_,f)) ->
 		add_feature ctx "use.$bind";
 		(match x.eexpr with
@@ -1309,6 +1315,12 @@ let generate com =
 		print ctx "function $bind(o,m) { if( m == null ) return null; if( m.__id__ == null ) m.__id__ = $fid++; var f; if( o.hx__closures__ == null ) o.hx__closures__ = {}; else f = o.hx__closures__[m.__id__]; if( f == null ) { f = function(){ return f.method.apply(f.scope, arguments); }; f.scope = o; f.method = m; o.hx__closures__[m.__id__] = f; } return f; }";
 		newline ctx;
 	end;
+	if has_feature ctx "use.$arrayPushClosure" then begin
+		print ctx "function $arrayPushClosure(a) {";
+		print ctx " return function(x) { a.push(x); }; ";
+		print ctx "}";
+		newline ctx
+	end;
 	List.iter (gen_block_element ~after:true ctx) (List.rev ctx.inits);
 	List.iter (generate_static ctx) (List.rev ctx.statics);
 	(match com.main with

+ 12 - 0
tests/unit/issues/Issue1997.hx

@@ -0,0 +1,12 @@
+package unit.issues;
+
+class Issue1997 extends Test {
+    function test() {
+        var arr = [];
+        [1,2,3].map(arr.push);
+        eq(arr.length, 3);
+        eq(arr[0], 1);
+        eq(arr[1], 2);
+        eq(arr[2], 3);
+    }
+}