Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(utils): 新增camelCase转换函数 #140

Merged
merged 3 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/types/Camelize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export type stringToCamelCase<S extends string> =
xixiIBN5100 marked this conversation as resolved.
Show resolved Hide resolved
S extends `${infer T}_${infer U}` ?
U extends "" ? `${T}_` : `${T}${stringToCamelCase<Capitalize<U>>}`
: S;

export type toCamelCase<T> = {
[Key in keyof T as stringToCamelCase<Key & string>]: T[Key] extends Array<infer G>
? Array<toCamelCase<G>>
: T[Key] extends object
? toCamelCase<T[Key]>
: T[Key]
};
20 changes: 20 additions & 0 deletions src/utils/camelize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { toCamelCase } from "@/types/Camelize";

function stringToCamelCase(str:string): string{

Check failure on line 3 in src/utils/camelize.ts

View workflow job for this annotation

GitHub Actions / cache-and-install

Expected a space after the ':'

Check failure on line 3 in src/utils/camelize.ts

View workflow job for this annotation

GitHub Actions / cache-and-install

Missing space before opening brace
return str.replace(/_([a-z])/g,(_match,letter) => {

Check failure on line 4 in src/utils/camelize.ts

View workflow job for this annotation

GitHub Actions / cache-and-install

A space is required after ','

Check failure on line 4 in src/utils/camelize.ts

View workflow job for this annotation

GitHub Actions / cache-and-install

A space is required after ','
return letter.toUpperCase();
});
}

export function toCamelCase<T>(obj: T): toCamelCase<T> {
if (Array.isArray(obj)) {
return obj.map(item => toCamelCase(item)) as toCamelCase<T>;
} else if (obj !== null && typeof obj === "object") {
return Object.keys(obj).reduce((acc, key) => {
const camelKey = stringToCamelCase(key);
acc[camelKey] = toCamelCase(obj[key]);
return acc;
}, {}) as toCamelCase<T>;
}
return obj as toCamelCase<T>;
}
Loading