Last active
June 20, 2017 20:34
-
-
Save harold-b/df24fc5f77e316e2a3c684097256fc8c to your computer and use it in GitHub Desktop.
Hacky haxe plain javascript object with JS for/in key value loop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package; | |
typedef Union2<T1,T2> = haxe.extern.EitherType<T1,T2>; | |
abstract JSObject( Dynamic ) from Dynamic to Dynamic | |
{ | |
public inline function new() | |
{ | |
this = {}; | |
} | |
@:arrayAccess | |
public inline function get( key:Union2<String,Int> ):Dynamic | |
{ | |
return untyped this[key]; | |
} | |
@:arrayAccess | |
public inline function set( key:Union2<String,Int>, value:Dynamic ) | |
{ | |
untyped this[key] = value; | |
} | |
public inline function forIn( body:String->Void ) | |
{ | |
untyped __js__( "for( var $k in {0} ) {1}", this, body(untyped $k) ); | |
} | |
public inline function delete( key:Union2<String,Int> ) | |
{ | |
untyped __js__( "delete {0}[{1}]", this, key ); | |
} | |
} |
See This comment for a nicer implementation for the for loop, with no need to defined your own var to hold the key
.
@back2dos's implementation:
class Test {
static function main() {
var o = { x: 1 , y: 2 };
forIn(o, function (s) {
trace(s);
});
}
static inline function forIn(target:Dynamic, body:String->Void) {
untyped __js__( "for (let $k in {0} ) {1}", target, body(untyped $k) );
}
}
Output:
(function () { "use strict";
var Test = function() { };
Test.main = function() {
var o = { x : 1, y : 2};
for (let $k in o ) console.log($k);
};
Test.main();
})();
Modified to reflect above method.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As of Haxe v 3.4, there's no native for( key in object ) loop generation, so this is a hacky way to accomplish it.