Skip to content

Instantly share code, notes, and snippets.

@harold-b
Last active June 20, 2017 20:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harold-b/df24fc5f77e316e2a3c684097256fc8c to your computer and use it in GitHub Desktop.
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.
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 );
}
}
@harold-b
Copy link
Author

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.

@harold-b
Copy link
Author

@harold-b
Copy link
Author

harold-b commented Mar 16, 2017

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();
})();

@harold-b
Copy link
Author

Modified to reflect above method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment