Skip to content

#13 - RemoveValues accepts multiple items and returns number of removed items#32

Merged
maciej-sz merged 3 commits intomainfrom
feat/#13/remove-values-upgrade
Mar 17, 2025
Merged

#13 - RemoveValues accepts multiple items and returns number of removed items#32
maciej-sz merged 3 commits intomainfrom
feat/#13/remove-values-upgrade

Conversation

@maciej-sz
Copy link
Copy Markdown
Contributor

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

Summary by CodeRabbit

  • Documentation

    • Refined goal description in the collections documentation for improved clarity.
  • New Features

    • Enhanced removal operations to support the removal of multiple values at once, now returning the count of items removed.
    • Upgraded overall handling of collection operations to offer a more efficient and reliable experience.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 17, 2025

Walkthrough

The update refines the documentation language and enhances the removal functionalities across multiple collection types. The changes update method signatures to accept variadic parameters and return the count of removed items. Both map-based and sequence-based implementations of the removal methods have been adjusted, with corresponding test cases expanded to cover these scenarios. Additionally, new utility methods for managing value counts have been introduced along with their tests. No alterations were made to the exported or public entities outside of updated comments and method signatures.

Changes

File(s) Change Summary
README.adoc Updated wording for the collections goal from “Reduce repetition in day-to-day collections operations” to “Reduce repetition of common collections operations”.
cmpmutable_cases_test.go Added new test cases for RemoveValues that include a new want3 field to verify the count of removed items for various multi-value removal scenarios.
definitions.go, mapcmp.go, sequencecmp.go Updated method signatures for RemoveValues (now accepts a variadic parameter and returns an int) and updated the comment for RemoveMatching to indicate it returns the removal count. Adjusted internal removal logic accordingly.
vc.go, vc_test.go Introduced two new methods in valuesCounter: Set(v V, count int) for adjusting counts (removing entries when count < 1) and IsEmpty() bool to check emptiness. Added a corresponding test to validate the zero count behavior.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Caller
    participant Collection as Collection (Map/Seq)

    Client->>Collection: RemoveValues(v1, v2, ... )
    Collection->>Collection: Build removal counter (toRemove)
    alt toRemove is empty
        Collection-->>Client: Return count = 0
    else
        Collection->>Collection: Iterate over items and apply removal predicate
        Collection->>Collection: Decrement counter and accumulate removal count
        Collection-->>Client: Return total removal count
    end
Loading

Poem

In my burrow of code, I happily bound,
Hopping through changes with a joyful sound.
Variadic magic now clears more with a leap,
Removing duplicates while the tests take a peep.
With each method refined, my heart does sing,
A rabbit’s code dance—a charming new spring!
🐇🌸

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 b1bb4e7 and e3a9690.

📒 Files selected for processing (5)
  • cmpmutable_cases_test.go (3 hunks)
  • mapcmp.go (1 hunks)
  • sequencecmp.go (1 hunks)
  • vc.go (2 hunks)
  • vc_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • mapcmp.go
🔇 Additional comments (12)
vc_test.go (1)

5-11: The test case looks good!

This test confirms that the Set method correctly removes entries when a count of 0 is provided. It's a clean, focused unit test that verifies a specific behavior.

vc.go (3)

3-5: Import formatting looks good.

The import statement has been reformatted to use a multi-line import block, which follows Go's standard formatting conventions.


37-43: Well-implemented Set method!

The Set method implementation is clear and handles the key logic: removing entries when count is less than 1, otherwise setting the count directly. This is exactly what we'd expect from a method named Set in this context.


45-47: Good utility method.

The IsEmpty method provides a clear and concise way to check if the counter is empty, which will be useful throughout the codebase.

cmpmutable_cases_test.go (4)

20-21: Properly added expected count verification to existing tests.

The want3 field has been systematically added to all existing test cases, with correct values matching the expected number of items that should be removed in each scenario.

Also applies to: 28-29, 36-37, 44-45, 52-53, 60-61, 68-69, 76-77, 84-85


86-125: Excellent expansion of test cases!

These new test cases comprehensively cover the various scenarios for the enhanced RemoveValues function, including:

  • Removing a single value via the new variadic parameter
  • Removing multiple values (two and three distinct values)
  • Handling cases where none of the specified values exist
  • Handling empty value arrays

This ensures the new functionality is thoroughly tested.


133-139: Well-structured testing logic.

The testing function has been properly updated to handle both the original single-value case and the new multiple-values case. The code elegantly determines which approach to use based on whether values is nil.


147-149: Good verification of return value.

Added assertion for the returned count matches expectations. This completes the test by verifying that the method not only modifies the collection correctly but also returns the expected count.

sequencecmp.go (4)

159-160: Good function signature update.

The method signature has been updated to accept variadic parameters and return the count of removed values, which aligns with the PR objective.


163-172: Efficient handling of removal tracking.

The implementation creates a counter to track values to be removed and their occurrences, which handles duplicates properly. The early return when no matching values are found is an excellent optimization.


174-182: Well-implemented removal logic.

The removal logic has been correctly modified to check against the toRemove counter, incrementing the removal count and decrementing the counter for each match. This approach efficiently handles multiple values and duplicates.


186-187: Good return value.

The method now correctly returns the count of removed items, which provides valuable information to the caller.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 17, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Files with missing lines Coverage Δ
definitions.go 100.00% <ø> (ø)
mapcmp.go 100.00% <100.00%> (ø)
sequencecmp.go 100.00% <100.00%> (ø)
vc.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: 0

🧹 Nitpick comments (2)
sequencecmp.go (1)

163-168: Consider optimizing counter initialization

The current implementation always creates a new counter and then checks each value individually. You could optimize this by only initializing the counter when at least one value to remove exists.

-	toRemove := newValuesCounter[V]()
-	for _, v := range v {
-		if c.vc.Count(v) > 0 {
-			toRemove.counter[v] = c.vc.Count(v)
-		}
-	}
+	var toRemove *valuesCounter[V]
+	for _, v := range v {
+		if c.vc.Count(v) > 0 {
+			if toRemove == nil {
+				toRemove = newValuesCounter[V]()
+			}
+			toRemove.counter[v] = c.vc.Count(v)
+		}
+	}
+
+	if toRemove == nil {
+		return 0
+	}
cmpmutable_cases_test.go (1)

133-138: Consider simplifying the test logic for RemoveValues

The conditional approach to call RemoveValues with either a single value or multiple values could be simplified. Since RemoveValues now accepts variadic parameters, you can simply handle all cases uniformly.

-			count := -1
-			if tt.args.values != nil {
-				count = tt.coll.RemoveValues(tt.args.values...)
-			} else {
-				count = tt.coll.RemoveValues(tt.args.value)
-			}
+			var count int
+			if tt.args.values != nil {
+				count = tt.coll.RemoveValues(tt.args.values...)
+			} else {
+				count = tt.coll.RemoveValues(tt.args.value)
+			}

Or even better, consider updating the testArgs struct to use a standardized approach for all cases:

// In the args struct definition (not shown in this file)
type testArgs[C any, V any] struct {
-	value  V
-	values []V
+	values []V // Use this for all cases
}

// Then update all test cases to use values instead of value
// And simplify the test function:
count := tt.coll.RemoveValues(tt.args.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 0158754 and 1f676c0.

📒 Files selected for processing (6)
  • README.adoc (1 hunks)
  • cmp.go (2 hunks)
  • cmpmutable_cases_test.go (3 hunks)
  • definitions.go (2 hunks)
  • mapcmp.go (1 hunks)
  • sequencecmp.go (1 hunks)
🔇 Additional comments (10)
cmp.go (2)

3-5: Import formatting looks good.

The multi-line import format makes the code more maintainable as additional imports are added in the future.


37-39: Great addition of the IsEmpty method.

This helper method provides a clean way to check if the counter contains any entries, improving the API's usability. The implementation correctly checks if the length of the counter map is zero.

README.adoc (1)

21-21: Improved goal description.

Changing from "day-to-day" to "common" collections operations provides a clearer description of the package's intent.

mapcmp.go (1)

219-234: Well-implemented enhancement to RemoveValues.

The method now accepts variadic parameters to remove multiple values in a single call and returns the count of removed items. The implementation is efficient:

  • Creates a counter for values to be removed
  • Only targets values that exist in the collection
  • Uses RemoveMatching with a predicate for actual removal
  • Properly tracks and decrements the removal counter

This change significantly improves the API's flexibility and provides valuable feedback to callers.

definitions.go (2)

92-93: Helpful clarification on return value.

Adding this comment clarifies the behavior of RemoveMatching by documenting that it returns the number of removed items.


139-140: Interface properly updated for RemoveValues.

The CmpMutable interface has been correctly updated to:

  1. Accept variadic parameters (...V)
  2. Return the count of removed items
  3. Include a clarifying comment

This change aligns with the implementation in mapcmp.go and provides a more flexible API.

sequencecmp.go (2)

159-188: Good implementation of variadic RemoveValues with count return

The refactored RemoveValues method now supports removing multiple values at once and returns the count of removed items. The implementation is efficient, using a counter approach to track removals.

A few observations:

  1. The use of toRemove.IsEmpty() as an early exit optimization is good.
  2. The counter-based approach properly handles duplicates in both the collection and the input values.

170-172:

Details

✅ Verification successful

Verify IsEmpty method exists on valuesCounter

The code references toRemove.IsEmpty(), but this method is not visible in the provided code. Ensure this method exists on the valuesCounter struct.


🏁 Script executed:

#!/bin/bash
# Check if IsEmpty() method exists on valuesCounter struct
grep -A 5 -B 5 "func.*valuesCounter.*IsEmpty" --include="*.go" -r .

Length of output: 248


IsEmpty method verified: No action needed

The execution confirmed that the IsEmpty() method exists on the valuesCounter struct (defined in cmp.go), so no changes are necessary in sequencecmp.go.

cmpmutable_cases_test.go (2)

86-125: Good comprehensive test coverage for variadic RemoveValues

The new test cases thoroughly cover various scenarios for multi-value removal, including:

  • Single value removal (using variadic syntax)
  • Multiple value removal with different quantities
  • Edge cases like empty value slices and non-existent values

This comprehensive test coverage ensures the new functionality works correctly across different scenarios.


147-149: Good validation of return value

The added verification of the returned count is essential for testing the new functionality. It ensures that the method not only modifies the collection correctly but also reports the number of removed items accurately.

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

219-237: Excellent implementation of variadic RemoveValues function!

The method has been updated to accept multiple values and return the count of removed items. The implementation uses an efficient approach by:

  1. Tracking values to be removed with a counter
  2. Early returning if nothing to remove
  3. Leveraging the existing RemoveMatching method

One minor suggestion: consider using encapsulation methods instead of direct access to the counter's internal data structure on line 223:

-			toRemove.counter[v] = c.vc.Count(v)
+			// Assuming there's an appropriate method like:
+			toRemove.Set(v, c.vc.Count(v))
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1f676c0 and b1bb4e7.

📒 Files selected for processing (1)
  • mapcmp.go (1 hunks)

@maciej-sz maciej-sz merged commit 65944f3 into main Mar 17, 2025
4 checks passed
@maciej-sz maciej-sz deleted the feat/#13/remove-values-upgrade branch March 17, 2025 21:32
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