From 2ba95b78d5a3c2122f131aed967179374ea900d0 Mon Sep 17 00:00:00 2001 From: Tomer Aberbach Date: Sat, 7 Dec 2024 19:18:07 -0500 Subject: [PATCH] feat: enums --- src/convert.ts | 4 +++- test/index.ts | 24 ++++++++++++++++++++++++ test/snapshots/enum/arbitraries.js | 7 +++++++ test/snapshots/enum/samples.js | 23 +++++++++++++++++++++++ 4 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 test/snapshots/enum/arbitraries.js create mode 100644 test/snapshots/enum/samples.js diff --git a/src/convert.ts b/src/convert.ts index 0063473..c1f8747 100644 --- a/src/convert.ts +++ b/src/convert.ts @@ -253,7 +253,9 @@ const convertEnum = ( name: pascalcase($enum.name || propertyName || `Enum`), values: pipe( $enum.members, - map(([, { value }]) => JSON.stringify(value)), + map(([, { name, value }]) => + JSON.stringify(value === undefined ? name : value), + ), reduce(toArray()), ), }) diff --git a/test/index.ts b/test/index.ts index f036f0e..b9f2810 100644 --- a/test/index.ts +++ b/test/index.ts @@ -353,6 +353,30 @@ test.each([ }, // Models + { + name: `enum`, + code: ` + enum $Enum { + A, + B, + C, + D, + } + enum StringEnum { + A: "a", + B: "b", + C: "c", + D: "d", + } + enum NumberEnum { + A: 1, + B: 2, + C: 3.14, + // https://github.com/microsoft/typespec/issues/5296 + D: 4${`0`.repeat(310)}, + } + `, + }, { name: `array`, code: ` diff --git a/test/snapshots/enum/arbitraries.js b/test/snapshots/enum/arbitraries.js new file mode 100644 index 0000000..7c5840c --- /dev/null +++ b/test/snapshots/enum/arbitraries.js @@ -0,0 +1,7 @@ +import * as fc from 'fast-check'; + +export const $Enum = fc.constantFrom("A", "B", "C", "D"); + +export const StringEnum = fc.constantFrom("a", "b", "c", "d"); + +export const NumberEnum = fc.constantFrom(1, 2, 3.14, null); \ No newline at end of file diff --git a/test/snapshots/enum/samples.js b/test/snapshots/enum/samples.js new file mode 100644 index 0000000..73f9e4d --- /dev/null +++ b/test/snapshots/enum/samples.js @@ -0,0 +1,23 @@ +export const samples = { + '$Enum': [ + 'C', + 'D', + 'B', + 'C', + 'A' + ], + 'NumberEnum': [ + 3.14, + null, + 2, + 3.14, + 1 + ], + 'StringEnum': [ + 'c', + 'd', + 'b', + 'c', + 'a' + ] +}; \ No newline at end of file