unique-objects-set
v1.0.2
Published
Ensure that all objects added to a JS Set are unique
Readme
🚀 UniqueObjectSet
A modern TypeScript utility that ensures all objects inside a Set are truly unique based on their content, not just their reference.
By default, JavaScript
Setonly considers objects unique by reference.UniqueObjectSetensures uniqueness by key-value equality.
📦 Installation
npm install unique-object-setOr with Yarn:
yarn add unique-object-set✨ Features
- ✅ Ensures true uniqueness of objects in a set
- ⚡ Lightweight and dependency-free
- 🛡️ Written in TypeScript with full type definitions
- 🌍 Works in Node.js and browser environments
🔥 Usage
Importing
import { UniqueObjectSet } from "unique-object-set";Basic Example
const set = new UniqueObjectSet();
set.add({ id: 1, name: "Alice" });
set.add({ id: 1, name: "Alice" }); // Duplicate by content, won't be added
set.add({ id: 2, name: "Bob" });
console.log(set.size); // 2Checking Existence
console.log(set.has({ id: 1, name: "Alice" })); // true
console.log(set.has({ id: 3, name: "Charlie" })); // falseDeleting an Object
set.delete({ id: 1, name: "Alice" });
console.log(set.size); // 1Iterating Over the Set
for (const item of set) {
console.log(item);
}⚙️ API
add(object: object): this
Adds an object to the set if it's not already present by content.
has(object: object): boolean
Checks if an object exists in the set based on content.
delete(object: object): boolean
Deletes an object from the set if it exists.
size: number
Returns the number of unique objects in the set.
[Symbol.iterator]()
Allows iteration using for...of loops.
🛠️ How It Works
UniqueObjectSet uses deep comparison (like JSON serialization) to ensure object uniqueness by their key-value pairs, not memory reference.
🧪 Testing
To run tests:
npm test📄 License
MIT
💡 Contributing
- Fork the project.
- Create your feature branch:
git checkout -b feature/my-feature - Commit your changes:
git commit -m 'feat: add new feature' - Push to the branch:
git push origin feature/my-feature - Open a pull request.
🤝 Support
Have questions or suggestions? Feel free to open an issue!
Made with ❤️ in TypeScript.
