Skip to content

Commit

Permalink
fix: Fix snake casing numbers. (#1052)
Browse files Browse the repository at this point in the history
Fixes #1048
  • Loading branch information
stephenh authored Jun 4, 2024
1 parent 63990c0 commit f85a2f1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
11 changes: 9 additions & 2 deletions src/case.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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 {
Expand Down
4 changes: 4 additions & 0 deletions tests/case-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit f85a2f1

Please sign in to comment.