@infini-pattern/core v1.0.11
@infini-pattern/core
This is a TypeScript implementation of a generic SL-GUARRD design pattern, a.k.a Slow guard
(Search, List, GroupBy, Update, Replace, Remove, Destroy) class, called USet. It can be used to store any type of entity that has an id property
Installation
To install USet, you can use npm:
npm install @infini-pattern/core
Alternatively, you can download the source code and include it in your project manually.
Usage
import { UEntity, USet } from "@infini-pattern/core";
interface User extends UEntity {
name: string;
age: number;
}
const set = new USet<User>();
// Add a new item
const user1 = set.add({ id: "1", name: "John", age: 30 });
// Update an existing item
set.update({ id: "1", name: "John Doe", age: 31 });
// Search for an item by ID
const user = set.search("1");
// List all items in the set
const users = set.list();
// Group the items in the set by a field
const usersByAge = set.groupBy("age");
// Remove an item by ID
const removedUser = set.remove("1");
// Destroy all items in the set
set.destroy();
API Reference
USet<T>
Properties
items: T[]
: An array of the items in the set.
Methods
search(id: string): T | undefined
: Searches for an item in the set by its ID. Returns the item with the specified ID, or undefined if no such item exists.list(): T[]
: Lists all items in the set. Returns an array of all the items in the set.groupBy(field: keyof T): Record<string, T[]>
: Groups the items in the set by a specified field. Returns an object where the keys are the values of the field and the values are arrays of items with the corresponding field value.update(item: T): T | undefined
: Updates an existing item in the set. Returns the updated item, or undefined if no such item exists.add(item: T): T
: Adds a new item to the set. Returns the added item.replace(item: T): T | undefined
: Replaces an existing item in the set with a new one. Returns the replaced item, or undefined if no such item exists.remove(id: string): T | undefined
: Removes an item from the set by its ID. Returns the removed item, or undefined if no such item exists.destroy(): void
: Destroys all items in the set.