1.2.0 • Published 9 months ago
@_greataxe/indexed-object v1.2.0
indexed-object
A TypeScript utility for working with indexed collections of objects. This package provides an efficient way to work with arrays of objects that have unique identifiers, offering features like indexing, sorting, filtering, and more.
Installation
npm install indexed-objectUsage
import { IndexedObject } from 'indexed-object';
// Create a new indexed collection
const users = new IndexedObject([
{ user_id: 1, name: 'John', age: 30 },
{ user_id: 2, name: 'Jane', age: 25 }
], 'user_id');
// Access by index
const firstUser = users.get(0);
// Access by ID
const userById = users.getById(2);
// Sort users by age
const sortedUsers = users.sortBy('age');
// Filter users
const filteredUsers = users.filterBy(user => user.age > 25);
// Add new user
users.add({ user_id: 3, name: 'Bob', age: 35 });
// Remove user
users.remove(2);
// Get original array
const array = users.toArray();
// Create a deep copy
const copy = users.deepCopy();Features
- Access items by index or ID
- Sort collection by any property
- Filter collection
- Add/remove items
- Convert to array
- Create deep copies
- TypeScript support
- Immutable operations (sort/filter return new instances)
API
Constructor
new IndexedObject<T>(data: T[], idKey: keyof T)Methods
get(index: number): T | undefined- Get item by indexgetById(id: any): T | undefined- Get item by IDsortBy(key: keyof T, direction?: 'asc' | 'desc'): IndexedObject<T>- Sort collectionfilterBy(predicate: (item: T) => boolean): IndexedObject<T>- Filter collectiontoArray(): T[]- Convert to arrayadd(item: T): void- Add new itemremove(id: any): boolean- Remove item by IDdeepCopy(): IndexedObject<T>- Create deep copy
License
MIT