Skip to content

Commit

Permalink
Keep C# enum value sequence
Browse files Browse the repository at this point in the history
As I could test, TypeScript folow the same C# sequence numbering when enum value is missing in declaring type.
  • Loading branch information
Rodrigo Cesar committed May 24, 2024
1 parent 82fcc81 commit a17fa43
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 4 deletions.
8 changes: 6 additions & 2 deletions converter.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,13 @@ const createConverter = config => {
} else {
rows.push(`export enum ${enum_.Identifier} {`);

entries.forEach(([key, value], i) => {
entries.forEach(([key, value]) => {
if (config.numericEnums) {
rows.push(` ${key} = ${value != null ? value : i},`);
if (value == null) {
rows.push(` ${key},`);
} else {
rows.push(` ${key} = ${value != null ? value : i},`);
}
} else {
rows.push(` ${key} = '${getEnumStringValue(key)}',`);
}
Expand Down
4 changes: 2 additions & 2 deletions lib/csharp-models-to-json/EnumCollector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@

namespace CSharpModelsToJson
{
class Enum
public class Enum
{
public string Identifier { get; set; }
public Dictionary<string, object> Values { get; set; }
}

class EnumCollector: CSharpSyntaxWalker
public class EnumCollector: CSharpSyntaxWalker
{
public readonly List<Enum> Enums = new List<Enum>();

Expand Down
43 changes: 43 additions & 0 deletions lib/csharp-models-to-json_test/EnumCollector_test.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NUnit.Framework;

namespace CSharpModelsToJson.Tests
{
[TestFixture]
public class EnumCollectorTest
{
[Test]
public void ReturnEnumWithMissingValues()
{
var tree = CSharpSyntaxTree.ParseText(@"
public enum SampleEnum
{
A,
B = 7,
C,
D = 4,
E
}"
);

var root = (CompilationUnitSyntax)tree.GetRoot();

var enumCollector = new EnumCollector();
enumCollector.VisitEnumDeclaration(root.DescendantNodes().OfType<EnumDeclarationSyntax>().First());

var model = enumCollector.Enums.First();

Assert.That(model, Is.Not.Null);
Assert.That(model.Values, Is.Not.Null);

var values = model.Values.ToArray();
Assert.That(values[0].Value, Is.Null);
Assert.That(values[1].Value, Is.EqualTo("7"));
Assert.That(values[2].Value, Is.Null);
Assert.That(values[3].Value, Is.EqualTo("4"));
Assert.That(values[4].Value, Is.Null);
}
}
}

0 comments on commit a17fa43

Please sign in to comment.