Skip to content

#13 - refactor: update Copy() function and interface implementations#24

Merged
maciej-sz merged 4 commits intomainfrom
feat/#13/update-copy
Mar 16, 2025
Merged

#13 - refactor: update Copy() function and interface implementations#24
maciej-sz merged 4 commits intomainfrom
feat/#13/update-copy

Conversation

@maciej-sz
Copy link
Copy Markdown
Contributor

@maciej-sz maciej-sz commented Mar 16, 2025

This PR focuses on refactoring the Copy() function implementation and making the internal interfaces more consistent, while removing unused code.

  • Modify Copy() to check for baseInternal interface implementation
  • Update copy() method signatures to return baseInternal[V] consistently
  • Remove unused KV-related types and functions
  • Remove comfyContainsValue and comfyContainsKV functions
  • Initialize empty slices with nil instead of make()
  • Add test cases for Copy() function and edge cases
  • Update interface definitions for mapInternal

Summary by CodeRabbit

  • Tests

    • Added a new test to validate correct behavior when evaluating collections in reversed order.
    • Introduced comprehensive unit tests for various collection operations, ensuring correct behavior of the Copy function.
  • Refactor

    • Enhanced collection operations with improved type safety and error management.
    • Streamlined the internal code by removing deprecated helper components, resulting in a more consistent and robust experience.

This commit focuses on refactoring the Copy() function implementation and making the internal interfaces more consistent, while removing unused code.

- Modify Copy() to check for baseInternal interface implementation
- Update copy() method signatures to return baseInternal[V] consistently
- Remove unused KV-related types and functions
- Remove comfyContainsValue and comfyContainsKV functions
- Initialize empty slices with nil instead of make()
- Add test cases for Copy() function and edge cases
- Update interface definitions for mapInternal
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 16, 2025

Walkthrough

This pull request introduces updates across tests, type definitions, interface methods, and utility functions. A new test case is added to validate the behavior of the Min() function on a reversed three-item collection. Several key-value related types and helper functions were removed. Multiple copy method signatures have been revised to return a unified baseInternal type (often parameterized with Pair) and the Copy function now asserts type compatibility, panicking if the collection does not implement the expected interface. Additionally, slice initializations in sequences were updated.

Changes

File(s) Change Summary
cmp_cases_test.go, sequence_test.go Added a new test case for checking Min() on a reversed three-item collection and updated sequence tests to expect nil slices instead of initialized empty slices.
definitions.go, functions_internal.go Removed key-value related types (KVVistor, KVPredicate, KVReducer) and the helper functions comfyContainsValue and comfyContainsKV.
definitions_internal.go, functions.go, map.go, mapcmp.go, sequence.go, sequencecmp.go Revised copy method signatures to return baseInternal (often with Pair parameters) and updated the Copy function to perform a type assertion with a panic on failure.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant CopyFunc as Copy()
    participant Coll as Collection Instance

    Caller->>CopyFunc: Call Copy(coll)
    CopyFunc->>Coll: Assert coll implements baseInternal?
    alt Assertion succeeds
        Coll-->>CopyFunc: Valid baseInternal instance
        CopyFunc->>Coll: Invoke copy() method
        Coll-->>CopyFunc: Return copied instance
        CopyFunc-->>Caller: Return copy result
    else Assertion fails
        CopyFunc-->>Caller: Panic with error message
    end
Loading

Poem

I’m a rabbit strolling in the code field,
Hopping through changes, nothing concealed.
Tests and methods now sing in rhyme,
Copy flows and types aligned in time.
With nibbling joy, I celebrate each new line! 🐇

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

Error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)
Failed executing command with error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 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 685a644 and dc637e3.

📒 Files selected for processing (1)
  • functions_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • functions_test.go

🪧 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.
  • @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.

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 16, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Files with missing lines Coverage Δ
definitions.go 100.00% <ø> (ø)
definitions_internal.go 100.00% <ø> (ø)
functions.go 100.00% <100.00%> (+100.00%) ⬆️
functions_internal.go 100.00% <ø> (+9.79%) ⬆️
map.go 100.00% <100.00%> (ø)
mapcmp.go 100.00% <100.00%> (ø)
sequence.go 100.00% <100.00%> (ø)
sequencecmp.go 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8588425 and 6d20af8.

📒 Files selected for processing (10)
  • cmp_cases_test.go (1 hunks)
  • definitions.go (0 hunks)
  • definitions_internal.go (2 hunks)
  • functions.go (1 hunks)
  • functions_internal.go (0 hunks)
  • map.go (1 hunks)
  • mapcmp.go (1 hunks)
  • sequence.go (2 hunks)
  • sequence_test.go (1 hunks)
  • sequencecmp.go (1 hunks)
💤 Files with no reviewable changes (2)
  • functions_internal.go
  • definitions.go
🧰 Additional context used
🪛 GitHub Check: codecov/patch
functions.go

[warning] 6-11: functions.go#L6-L11
Added lines #L6 - L11 were not covered by tests

🔇 Additional comments (9)
sequencecmp.go (1)

352-352: Return type changed to align with interface consistency

The return type of the copy() method has been updated from Base[V] to baseInternal[V] to ensure consistency with other collection implementations in the codebase.

sequence_test.go (1)

99-99: Improved initialization pattern for empty slices

The test expectations now use []int(nil) and []string(nil) instead of make([]int, 0) and make([]string, 0), which aligns with the new preferred pattern of initializing empty slices with nil throughout the codebase. This change is consistent with the implementation changes in the NewSequence function.

Also applies to: 107-107

cmp_cases_test.go (1)

370-374: Good addition of a test case for reversed collection

Adding a test case for the Min() function on a reversed three-item collection increases test coverage and ensures the function works correctly regardless of element order. This validates that the Min() function properly finds the minimum value even when the collection elements are in descending order.

mapcmp.go (1)

410-410: Return type updated for consistency across interfaces

The return type of copy() has been updated from mapInternal[K, V] to baseInternal[Pair[K, V]], which is part of the broader effort to standardize return types of copy methods across the codebase. This change improves interface consistency and makes the type system more coherent.

map.go (1)

328-342: Return type correctly updated to match interface changes

The return type of the copy() method has been properly updated from mapInternal[K, V] to baseInternal[Pair[K, V]] to align with the interface definition changes. The implementation correctly creates a deep copy of the map's data structures.

sequence.go (2)

15-15: Slice initialization optimized to use nil instead of make()

Using []V(nil) instead of make([]V, 0) is a good practice as it reduces memory allocation for empty slices. Both approaches create an empty slice, but the nil slice has a smaller memory footprint until elements are added.


260-267: Return type correctly updated to match interface changes

The return type has been properly updated from Base[V] to baseInternal[V] to align with the updated interface definition. This ensures type consistency across the implementation.

definitions_internal.go (2)

12-12: Interface return type updated for better type specificity

The return type of the copy() method in the baseInternal interface has been changed from Base[V] to baseInternal[V]. This makes the contract more precise by ensuring that the returned value implements the full baseInternal interface rather than just the less specific Base interface.


68-68: Interface streamlined by inheriting copy method from baseInternal

The copy() method declaration has been removed from the mapInternal interface and replaced with the inherited baseInternal[Pair[K, V]] interface embedding. This change eliminates interface redundancy while still ensuring that map types implement a proper copy method that returns a compatible type.

Comment on lines +6 to +11
func Copy[C Base[V], V any](coll C) C {
// check if c is of type baseInternal[T]:
if c, ok := any(coll).(baseInternal[V]); ok {
return c.copy().(C)
}
panic("Copy() requires a collection that implements the baseInternal interface")
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

❓ Verification inconclusive

Copy function improved with better type safety

The Copy function now accepts a broader type parameter C Base[V] while still enforcing that the implementation must satisfy the baseInternal[V] interface at runtime. This provides more flexibility while maintaining type safety. Good improvement!

The static analysis indicates this code isn't covered by tests. Consider adding test cases specifically for the new panic scenario to ensure full coverage.


🏁 Script executed:

#!/bin/bash
# Check if there are tests covering this new implementation
rg -A 10 -B 10 "TestCopy" --type go

Length of output: 35


Action Required: Add Tests for the Copy Function’s Panic Scenario

The updated Copy function in functions.go (lines 6–11) improves type safety by leveraging generics and enforcing at runtime that the collection implements the baseInternal[V] interface. However, our search for tests (via the rg -A 10 -B 10 "TestCopy" --type go command) produced no output—suggesting that the new behavior, especially the panic scenario, isn’t covered by any test cases.

  • Please add tests that verify the function’s behavior in both valid cases (successful copy when the type assertion passes) and invalid cases (triggering the panic with the message "Copy() requires a collection that implements the baseInternal interface" when the check fails).
  • Ensure that the panic scenario is properly caught (using, for instance, a dedicated test case that expects a panic) to achieve full coverage for this change.
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 6-11: functions.go#L6-L11
Added lines #L6 - L11 were not covered by tests

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
functions_test.go (3)

82-84: Minor typo in error message

There's a small typo in the error message where "want1" is used instead of "want".

-				t.Errorf("Copy() = %v, want1 %v", got, tt.coll)
+				t.Errorf("Copy() = %v, want %v", got, tt.coll)

110-112: Minor typo in error message

The same typo appears in this error message as well.

-				t.Errorf("Copy() = %v, want1 %v", got, tt.coll)
+				t.Errorf("Copy() = %v, want %v", got, tt.coll)

57-131: Consider adding deeper verification to Copy tests

While the current tests verify basic equality between the original and copied collections, they don't verify that the copies are truly independent objects (i.e., that modifying one doesn't affect the other). Consider adding additional assertions that modify the copy and verify the original remains unchanged.

Example addition to a test case:

t.Run("Copies are independent", func(t *testing.T) {
    original := NewSequenceFrom([]int{1, 2, 3})
    copied := Copy(original)
    
    // Modify the copy
    if seq, ok := copied.(Sequence[int]); ok {
        seq.Add(4)
        
        // Verify original is unchanged
        if reflect.DeepEqual(seq, original) {
            t.Error("Modifying copy affected the original")
        }
        
        // Verify original length is still 3
        if original.Len() != 3 {
            t.Errorf("Original length changed: got %d, want 3", original.Len())
        }
    } else {
        t.Error("Copied value couldn't be cast to Sequence[int]")
    }
})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6d20af8 and ada88c6.

📒 Files selected for processing (1)
  • functions_test.go (1 hunks)
🔇 Additional comments (5)
functions_test.go (5)

1-7: LGTM: Appropriate imports for test functionality

The imports include all necessary packages for testing, including iter for sequence operations, reflect for deep equality checks, and the standard testing library.


9-55: Well-designed mock struct for negative test case

The baseFakeWithoutInternal struct correctly implements all expected methods of a collection while deliberately not implementing the baseInternal interface, making it perfect for testing the new interface check in the Copy() function.


57-87: LGTM: Comprehensive tests for flat collections

This test case covers both empty and populated instances of Sequence and CmpSequence, ensuring the Copy() function works properly across different collection types.


89-115: LGTM: Well-structured tests for map collections

This test correctly verifies that Copy() works properly for both empty and populated Map collections.


117-131: LGTM: Effective panic test for interface requirement

This test properly verifies that the Copy() function panics with the expected error message when given a collection that doesn't implement the required baseInternal interface. The defer/recover pattern is an appropriate way to test panic conditions in Go.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

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 (1)
functions_test.go (1)

57-95: Good test coverage for linear collections with proper deep copy verification.

The test checks both empty and populated collections, and verifies that:

  1. The copied collection equals the original
  2. Modifying the original doesn't affect the copy (deep copy verification)
  3. Length checks confirm independent copies

One small issue in the error message:

if got.Len() == tt.coll.Len() {
    t.Errorf("Original length changed: got %d, want 3", got.Len())
}

The error message suggests we expect length 3, but this isn't always true for all test cases.

- t.Errorf("Original length changed: got %d, want 3", got.Len())
+ t.Errorf("Copy length %d should be different from original length %d after modification", got.Len(), tt.coll.Len())
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ada88c6 and 685a644.

📒 Files selected for processing (1)
  • functions_test.go (1 hunks)
🔇 Additional comments (3)
functions_test.go (3)

1-7: Package and imports look good.

The imports include necessary packages for testing and type reflection, which are appropriate for this test file.


9-55: Well-structured mock type for testing interface requirements.

The baseFakeWithoutInternal[V] type correctly implements the Base[V] interface but intentionally omits the baseInternal[V] interface to test error handling. All methods have minimal implementations that return zero values or no-op behavior, which is appropriate for this test case.


137-151: Good error case testing for Copy() with invalid collection type.

The test properly checks for panic behavior when Copy() is called with a collection that doesn't implement the baseInternal interface. The test verifies both that a panic happens and that the panic message is correct.

@maciej-sz maciej-sz merged commit 7bbe17c into main Mar 16, 2025
4 checks passed
@maciej-sz maciej-sz deleted the feat/#13/update-copy branch March 16, 2025 16:34
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