zspitz / ExpressionTreeToString

String representations of expression trees + library of expression tree objects
MIT License
151 stars 12 forks source link

JavaScript notation? #87

Open StefH opened 3 years ago

StefH commented 3 years ago

Describe the solution you'd like
Would it be possible to add a "JavaScript" formatter to write a valid JavaScript notation?

Expression<Func<double, int, double[], FormattableString>> ex = (value, index, values) => $"{(value < 1000 ? value : (value / 1000.0) + " K")}";

should be converted to:

`$(value < 1000 ? value : (value / 1000) + ' K'`
zspitz commented 3 years ago

It's certainly possible. Could you better clarify what's your use case?

Also, specifically WRT your example, my initial thinking would be as follows:

Expression<Func<double, int, double[], FormattableString>> ex = (value, index, values) => $"{(value < 1000 ? value : (value / 1000.0) + " K")}";
Console.WriteLine(ex.ToString("Javascript");
/*
    (value, index, values) => `$(value < 1000 ? value : (value / 1000) + ' K'`;
*/

and it would render the same whether the expression's return type is FormattableString or string, because in either case Javascript template literal syntax corresponds most closely to string interpolation.

But you could get the result you describe by using the LambdaExpression.Body property:

Expression<Func<double, int, double[], FormattableString>> ex = (value, index, values) => $"{(value < 1000 ? value : (value / 1000.0) + " K")}";
Console.WriteLine(ex.Body.ToString("Javascript");
/*
    `$(value < 1000 ? value : (value / 1000) + ' K'`
*/

Would this work for you?

zspitz commented 3 years ago

@StefH Any further thoughts on this?