From f85a2f1ed4e04143b96d6eaa3a589b16944d3239 Mon Sep 17 00:00:00 2001 From: Stephen Haberman Date: Tue, 4 Jun 2024 08:55:00 -0500 Subject: [PATCH] fix: Fix snake casing numbers. (#1052) Fixes #1048 --- src/case.ts | 11 +++++++++-- tests/case-test.ts | 4 ++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/case.ts b/src/case.ts index 09e270415..ef1b2eff2 100644 --- a/src/case.ts +++ b/src/case.ts @@ -1,4 +1,4 @@ -import { camelCase as camelCaseAnything, snakeCase as snakeCaseAnything } from "case-anything"; +import { camelCase as camelCaseAnything } from "case-anything"; import { Options } from "./options"; @@ -24,7 +24,14 @@ export function snakeToCamel(s: string): string { } export function camelToSnake(s: string): string { - return snakeCaseAnything(s).toUpperCase(); + return ( + s + // any number or little-char -> big char + .replace(/[a-z0-9]([A-Z])/g, (m) => m[0] + "_" + m[1]) + // any multiple big char -> next word + .replace(/[A-Z]([A-Z][a-z])/g, (m) => m[0] + "_" + m.substring(1)) + .toUpperCase() + ); } export function capitalize(s: string): string { diff --git a/tests/case-test.ts b/tests/case-test.ts index e9666926f..e701d2e2a 100644 --- a/tests/case-test.ts +++ b/tests/case-test.ts @@ -59,6 +59,10 @@ describe("case", () => { expect(camelToSnake("getAPIValue")).toEqual("GET_API_VALUE"); }); + it("converts string to snake case respecting number separation, getV1Foo === GET_V1_FOO", () => { + expect(camelToSnake("getV1Foo")).toEqual("GET_V1_FOO"); + }); + describe("getFieldJsonName", () => { it("keeps snake case when jsonName is probably not set", () => { expect(getFieldJsonName({ name: "foo_bar", jsonName: "fooBar" }, { snakeToCamel: [], useJsonName: false })).toBe(