Last active
October 22, 2020 14:37
-
-
Save serjek/c1e30a5812e316c2fe105d7df82ef51c to your computer and use it in GitHub Desktop.
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; | |
import haxe.macro.*; | |
using haxe.macro.ExprTools; | |
class MainTest { | |
static function main() { | |
var data1 = {hello:'world'}; | |
var data2 = {foo:'bar', hello: null}; | |
var data3:Dynamic = null; | |
var m = getVal(data1.hello); | |
var n = getVal(data2.hello); | |
var l = getVal(data3.hello.foo.bar, "baz"); | |
trace(m); | |
trace(n); | |
trace(l); | |
//array access | |
trace(get(data3.foo[0].length, 10)) | |
} | |
macro static function get(v:Expr, fallback:Expr = null) { | |
var arr = ~/(\.|\[)/g.split(v.toString()); | |
var added = ""; | |
var list = [ | |
for (prop in arr) { | |
if (added != "" && prop.indexOf(']') == -1) added += '.'; | |
//array access check | |
if (prop.indexOf(']') != -1) { | |
added += '['; | |
} | |
added += prop; | |
added; | |
} | |
]; | |
var ret = ''; | |
for (prop in list) { | |
if (ret != '') ret += ' && '; | |
ret += '$prop != null'; | |
} | |
ret += ' ? ${v.toString()} : ${fallback.toString()}'; | |
return Context.parse(ret, Context.currentPos()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment