Skip to content

Instantly share code, notes, and snippets.

@explorigin
Last active August 29, 2015 14:19
Show Gist options
  • Save explorigin/78b271fddab819fcda4c to your computer and use it in GitHub Desktop.
Save explorigin/78b271fddab819fcda4c to your computer and use it in GitHub Desktop.
Example of Optimized Javascript Object as a StringMap<Dynamic>
package project;
abstract JSObjectStringMap({}) {
public inline function new(?i:{}) {
this = if (i == null) {} else i;
}
}
package starlight.core;
import haxe.macro.Expr;
import haxe.macro.ExprTools;
import starlight.core.JSObjectStringMap;
class JSObjectStringMapTools {
macro public static inline function set(obj:ExprOf<JSObjectStringMap>, field:ExprOf<String>, value:Expr) {
return macro untyped __js__('${ExprTools.toString(obj)}[${ExprTools.toString(field)}] = ${ExprTools.toString(value)}');
}
macro public static inline function get(obj:ExprOf<JSObjectStringMap>, field:ExprOf<String>) {
return macro untyped __js__('${ExprTools.toString(obj)}[${ExprTools.toString(field)}]');
}
macro public static inline function exists(obj:ExprOf<JSObjectStringMap>, field:ExprOf<String>) {
return macro untyped __js__('${ExprTools.toString(field)} in ${ExprTools.toString(obj)}');
}
macro public static inline function keys(obj:ExprOf<JSObjectStringMap>) {
return macro (untyped __js__('Object.keys(${ExprTools.toString(obj)})'):Array<String>);
}
macro public static inline function arrayKeys(obj:ExprOf<JSObjectStringMap>) {
return macro (untyped __js__('Object.keys(${ExprTools.toString(obj)})'):Array<String>);
}
macro public static inline function size(obj:ExprOf<JSObjectStringMap>) {
return macro untyped __js__('Object.keys(${ExprTools.toString(obj)}).length');
}
macro public static function values(obj:ExprOf<JSObjectStringMap>):ExprOf<Array<Dynamic>> {
return macro [for (key in (untyped __js__('Object.keys(${ExprTools.toString(obj)})'):Array<String>)) (untyped __js__('${ExprTools.toString(obj)}[key]'))];
}
}
package project;
import JSObjectStringMap;
import JSObjectStringMapTools;
class App extends Lens {
static function main() {
var a = new JSObjectStringMap(); // compiles to: var a = { };
JSObjectStringMapTools.set(a, 'a', 1); // compiles to: a['a'] = 1;
JSObjectStringMapTools.keys(a); // compiles to: Object.keys(a);
}
}
@explorigin
Copy link
Author

I'm leaving this here for reference from the mailinglist. I recommend using DynamicAccess in the standard library instead.

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