jurassic
jurassic copied to clipboard
Wiki page "Supported types" does not mention ConcatenatedString
Hi,
the Wiki page Supported types shows which JS type maps to which .NET type. The table contains an entry for JS type string which maps to .NET type System.String.
However, I found that sometimes Jurassic supplies an Jurassic.ConcatenatedString instead of a regular System.String when calling a function, if the JS string has been constructed using the + operator. E.g.:
ScriptEngine engine = new ScriptEngine();
engine.SetGlobalFunction("myFunc", new Action<object>(arg =>
{
Console.WriteLine(arg.GetType() + ": " + arg.ToString());
}));
engine.Execute(@"
myFunc('abc');
myFunc('ab' + 'c');
");
displays:
System.String: abc
Jurassic.ConcatenatedString: abc
I think this could be added to the wiki page to avoid confusion. (When the .NET declares the parameter as string Jurassic automatically converts it to a string, but not when declaring it as object which is sometimes needed if the function should allow parameters of different types.)
Should I add this to the Wiki page? Thanks!
Yes, you're right, this is a bit of a trap. ConcatenatedString is intended as a performance optimization, for when you are concatenating in a loop, like this:
s = "start";
for (var i; i < 15; i ++) { s += ", " + i; }
// do something with s
This results in only three strings (and a StringBuilder) being created, rather than the naïve approach, which creates ~30.
Rather than changing the docs, I would rather treat this as a bug and convert ConcatenatedString to a regular string before passing it to the user-defined function.
For now, you can use TypeUtilities.TypeOf() and TypeConverter.ToString() to deal with strings & concatenated strings in a generic way. (There's also TypeUtilities.IsString() but that's internal...)