Skip to content

feat(toCase): add ToKebabCase and ToSakeCase and ArrayContains#7

Open
dziekonskik wants to merge 2 commits into
mainfrom
feat/string--toCase-and-ArrayContains
Open

feat(toCase): add ToKebabCase and ToSakeCase and ArrayContains#7
dziekonskik wants to merge 2 commits into
mainfrom
feat/string--toCase-and-ArrayContains

Conversation

@dziekonskik

@dziekonskik dziekonskik commented Jan 21, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Added ArrayContains type utility to check if a value exists in an array at the type level.
    • Introduced ToKebabCase type for converting string types to kebab-case format.
    • Added ToSnakeCase type for converting string types to snake_case format.
  • Refactor

    • Updated type definitions in strToArr/algo.ts for improved clarity and syntax.
  • Tests

    • Added comprehensive type tests for ArrayContains, ToKebabCase, and ToSnakeCase type utilities.

@dziekonskik dziekonskik requested a review from HideoKun January 21, 2025 19:46
@coderabbitai

coderabbitai Bot commented Jan 21, 2025

Copy link
Copy Markdown

Walkthrough

The pull request introduces several TypeScript type utilities focused on string and array manipulation. A new ArrayContains type is added to check if a value exists in an array, along with comprehensive type tests. The project also expands its string transformation capabilities by introducing ToKebabCase and ToSnakeCase types, which provide type-level conversions between different string case formats. Additionally, minor syntactical refinements are made to existing type definitions, enhancing overall clarity and maintainability.

Changes

File Change Summary
src/array/arrayContains/algo.ts Added recursive conditional type _ArrayContains for type-level array value checking
src/array/arrayContains/index.ts Introduced ArrayContains type with JSDoc documentation
src/array/arrayContains/index.test.ts Added comprehensive type tests for ArrayContains
src/string/strToArr/algo.ts Minor syntactical refinements to type definitions
src/string/toKebabCase/algo.ts Added _ToKebabCase type for converting strings to kebab-case
src/string/toKebabCase/index.ts Introduced ToKebabCase type alias
src/string/toKebabCase/index.test.ts Added extensive type tests for ToKebabCase
src/string/toSnakeCase/algo.ts Added _ToSnakeCase type for converting strings to snake_case
src/string/toSnakeCase/index.ts Introduced ToSnakeCase type alias
src/string/toSnakeCase/index.test.ts Added comprehensive type tests for ToSnakeCase

Sequence Diagram

sequenceDiagram
    participant Type as Type System
    participant ArrayContains as ArrayContains<A, V>
    participant ToKebabCase as ToKebabCase<Str>
    participant ToSnakeCase as ToSnakeCase<Str>

    Type->>ArrayContains: Check value existence
    ArrayContains-->>Type: Return boolean
    
    Type->>ToKebabCase: Convert string case
    ToKebabCase-->>Type: Return kebab-case string type
    
    Type->>ToSnakeCase: Convert string case
    ToSnakeCase-->>Type: Return snake_case string type
Loading

Poem

🐰 Hop, hop, through types we dance,
Transforming strings with rabbit's glance,
Arrays that know their hidden treasure,
Kebab and snake, we parse with pleasure!
Type magic springs from code's romance 🔮


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6b1d965 and 212ae46.

📒 Files selected for processing (2)
  • src/string/toKebabCase/index.ts (1 hunks)
  • src/string/toSnakeCase/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/string/toKebabCase/index.ts
  • src/string/toSnakeCase/index.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (14)
src/string/toSnakeCase/algo.ts (3)

4-4: Add JSDoc comment to document the Separators type.

Consider adding documentation to explain the purpose and usage of the Separators type.

+/** Array of characters that are considered as word separators in the input string */
 type Separators = [" ", "_", "-"]

6-11: Add JSDoc comment to document the Sanitize type.

The Sanitize type implementation looks good, but would benefit from documentation explaining its purpose and edge cases it handles.

+/**
+ * Sanitizes the final snake_case string by:
+ * 1. Removing leading underscores
+ * 2. Replacing consecutive underscores with a single underscore
+ * 3. Converting the result to lowercase
+ */
 type Saintize<Result extends string> =

Also, consider fixing the typo in the type name from Saintize to Sanitize.


13-25: Add JSDoc comment and consider performance optimization.

The implementation looks correct but would benefit from documentation and potential performance optimization.

+/**
+ * Converts a string literal type to snake_case.
+ * Handles:
+ * - camelCase/PascalCase to snake_case
+ * - Spaces, hyphens, and underscores as separators
+ * - Multiple consecutive separators
+ * - Leading/trailing separators
+ * @example
+ * type T = _ToSnakeCase<"camelCase"> // "camel_case"
+ */
 export type _ToSnakeCase<
   Str extends string,
   Builder extends string = "",
 > = Str extends `${infer First}${infer Rest}`

Consider using a lookup type for better performance with large strings:

type UpperToSnakeCase = {
  [K in string]: K extends Uppercase<K> 
    ? `_${Lowercase<K>}` 
    : K
}
src/string/toSnakeCase/index.test.ts (1)

8-91: Consider adding more edge cases to the test suite.

The test coverage is comprehensive, but consider adding these additional test cases:

+  it("should handle strings with numbers", () => {
+    type T1 = _ToSnakeCase<"user123Name">
+    type T2 = _ToSnakeCase<"123UserName">
+    expectTypeOf<T1>().toEqualTypeOf<"user123_name">()
+    expectTypeOf<T2>().toEqualTypeOf<"123_user_name">()
+  })

+  it("should handle single character strings", () => {
+    type T1 = _ToSnakeCase<"A">
+    type T2 = _ToSnakeCase<"a">
+    expectTypeOf<T1>().toEqualTypeOf<"a">()
+    expectTypeOf<T2>().toEqualTypeOf<"a">()
+  })
src/string/strToArr/algo.ts (2)

1-4: Add JSDoc documentation for the type utility.

Consider adding documentation to explain the purpose, usage, and examples of this string-to-array conversion utility.

Example documentation:

/**
 * Converts a string into an array of characters.
 * 
 * @template Str - The input string type
 * @template Acc - The accumulator array type
 * @example
 * type Result = _StrToArr<"hello", []> // ["h", "e", "l", "l", "o"]
 */

8-9: Consider renaming _StrToArr_Back$ for clarity.

The Back$ suffix in the type name is unclear. Consider a more descriptive name that reflects its purpose as an entry point or initializer.

Example alternatives:

  • _InitStrToArr
  • _CreateStrToArr
src/array/arrayContains/algo.ts (1)

1-13: Add JSDoc documentation for the algorithm.

Consider adding documentation to explain the recursive array traversal algorithm and its type parameters.

Example documentation:

/**
 * Internal type that recursively checks if a value exists in an array.
 * 
 * @template Array - The input array type
 * @template Value - The value type to search for
 * @template IndexArr - Array tracking the current index in recursion
 * @example
 * type Result = _ArrayContains<[1, 2, 3], 2, []> // true
 */
src/array/arrayContains/index.ts (1)

12-12: Fix typo in example documentation.

The second example uses StartsWith instead of ArrayContains.

- type ArrayContainsFalse = StartsWith<[true, true, false], false>; // Result: true
+ type ArrayContainsFalse = ArrayContains<[true, true, false], false>; // Result: true
src/string/toKebabCase/algo.ts (3)

4-4: Consider renaming Separators to be more specific.

The type name could be more descriptive to indicate its purpose in the kebab case conversion.

-type Separators = [" ", "_", "-"]
+type KebabCaseSeparators = [" ", "_", "-"]

6-11: Fix typo in type name Saintize.

The type name appears to have a typo - it should be Sanitize.

-type Saintize<Result extends string> =
+type Sanitize<Result extends string> =
   Result extends `-${infer Rest}`
-    ? Saintize<Rest>
+    ? Sanitize<Rest>
     : Result extends `${infer P}--${infer Q}`
-      ? Saintize<`${P}-${Q}`>
+      ? Sanitize<`${P}-${Q}`>
       : Uncapitalize<Result>

13-25: Consider adding JSDoc comments for the type utility.

The _ToKebabCase type utility would benefit from documentation explaining its purpose, parameters, and usage examples.

+/**
+ * Converts a string to kebab-case at type level.
+ * @example
+ * type T = _ToKebabCase<"helloWorld"> // "hello-world"
+ */
 export type _ToKebabCase<
   Str extends string,
   Builder extends string = "",
 > = ...
src/string/toKebabCase/index.test.ts (1)

8-91: Consider adding more edge cases to the test suite.

The test suite is comprehensive but could benefit from additional edge cases:

  1. Strings containing numbers (e.g., "hello123World")
  2. Empty strings with separators (e.g., "---")
  3. Special characters (e.g., "hello@World")

Example additional test cases:

it("should handle strings with numbers and special characters", () => {
  type T1 = _ToKebabCase<"hello123World">
  type T2 = _ToKebabCase<"hello@World">
  type T3 = _ToKebabCase<"---">
  expectTypeOf<T1>().toEqualTypeOf<"hello123-world">()
  expectTypeOf<T2>().toEqualTypeOf<"hello@-world">()
  expectTypeOf<T3>().toEqualTypeOf<"">()
})
src/array/arrayContains/index.test.ts (2)

25-27: Fix incorrect comment for test case.

The comment "false is in the array" contradicts the test name "should return false if the array does not contain the element".

-    > // false is in the array
+    > // checking for false in array containing true

90-103: Improve test description for type compatibility checks.

The test description "should return false for arrays that do not match the specified type" could be more precise as it's testing type literals against type definitions.

-  it("should return false for arrays that do not match the specified type", () => {
+  it("should return false when checking type definitions against arrays of primitive values", () => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2ecdf95 and 6b1d965.

📒 Files selected for processing (10)
  • src/array/arrayContains/algo.ts (1 hunks)
  • src/array/arrayContains/index.test.ts (1 hunks)
  • src/array/arrayContains/index.ts (1 hunks)
  • src/string/strToArr/algo.ts (1 hunks)
  • src/string/toKebabCase/algo.ts (1 hunks)
  • src/string/toKebabCase/index.test.ts (1 hunks)
  • src/string/toKebabCase/index.ts (1 hunks)
  • src/string/toSnakeCase/algo.ts (1 hunks)
  • src/string/toSnakeCase/index.test.ts (1 hunks)
  • src/string/toSnakeCase/index.ts (1 hunks)
🔇 Additional comments (4)
src/string/toSnakeCase/index.ts (1)

3-4: LGTM! Clean and well-structured type export.

The type export follows best practices with a clear separation between the public API and internal implementation.

src/string/toKebabCase/index.ts (1)

1-4: LGTM! Clean and follows TypeScript naming conventions.

The implementation correctly follows the TypeScript naming convention of using underscore prefix for internal types while exposing a clean public API.

src/array/arrayContains/index.ts (1)

17-20: LGTM! Clean public API with proper type constraints.

The implementation provides a user-friendly interface while correctly delegating to the internal implementation.

src/string/toKebabCase/index.test.ts (1)

69-70: Fix inconsistent test case for uppercase strings.

The expected output for "UPPERCASE" creates unnecessary hyphens between each letter. Consider if this is the desired behavior.

The current implementation produces "u-p-p-e-r-c-a-s-e" but a more intuitive result might be "uppercase". Please verify if this is intentional.

: _ArrayContains<
Array,
Value,
[...IndexArr, 7]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Replace magic number with 1 for index increment.

The index array is being incremented with 7 which seems incorrect. For array traversal, the index should be incremented by 1.

-        [...IndexArr, 7]
+        [...IndexArr, 1]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
[...IndexArr, 7]
[...IndexArr, 1]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant