Skip to content

Conversation

@sivaratrisrinivas
Copy link

This adds a uniquifySorted function to remove duplicates from sorted arrays. The function has O(n) time complexity and works with uint256, address, and bytes32 array types. This is particularly useful when mappings cannot be utilized, and provides an easy way to combine Array.sort() + Array.uniquifySorted().

Fixes #5520

Fixes #????

PR Checklist

  • Tests
  • Documentation
  • Changeset entry (run npx changeset add)

This adds a uniquifySorted function to remove duplicates from sorted arrays. The function has O(n) time complexity and works with uint256, address, and bytes32 array types. This is particularly useful when mappings cannot be utilized, and provides an easy way to combine Array.sort() + Array.uniquifySorted().

Fixes OpenZeppelin#5520

Co-Authored-By: Srinivas Sivaratri <[email protected]>
@changeset-bot
Copy link

changeset-bot bot commented Feb 27, 2025

⚠️ No Changeset found

Latest commit: e57bd0e

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@socket-security
Copy link

New, updated, and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/[email protected] 🔁 npm/[email protected] Transitive: eval, unsafe +254 212 MB kanej

View full report↗︎

Comment on lines +508 to +513
// Resize the array by creating a new one (can't modify length of memory arrays directly)
uint256[] memory result = new uint256[](resultSize);
for (uint256 i = 0; i < resultSize; ++i) {
result[i] = array[i];
}
return result;
Copy link
Collaborator

Choose a reason for hiding this comment

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

If it is agreed that modifying the array passed by reference is the right approach, then we should not do that copy. Instead, we should just resize (down) the array. unsafeSetLength does that.

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.

Add Array.uniquifySorted to the Arrays library

2 participants