adaptive-set
TypeScript icon, indicating that this package has built-in type declarations

0.2.0 • Public • Published

adaptive-set

Docs Build Status npm-version Coverage Status minified-size

A set of utils for implementing specialized Set data structure designed to optimize memory usage and performance based on the number of elements it contains. It adapts its internal representation to efficiently handle cases where there are no items, a single item, or multiple items.

  • No Items: When the set is empty, it uses an undefined value to represent the absence of elements, minimizing memory usage.
  • Single Item: When the set contains exactly one item, it uses a array [item] to store the single element, providing quick access and iteration.
  • Multiple Items: When the set contains more than one item, it switches to using a standard Set to leverage its efficient handling of multiple elements.

This adaptive approach ensures that the it remains efficient and performant across different usage scenarios, making it an ideal choice for applications where the number of elements can vary significantly.

Install

npm add adaptive-set

Example

import { add, has, remove, size, type AdaptiveSet } from "adaptive-set";

type Fn = () => void;

class MyClass {
  private listeners?: AdaptiveSet<Fn>;

  public notify(): void {
    if (this.listeners) {
      for (const listener of this.listeners) {
        listener();
      }
    }
  }

  public addListener(listener: Fn): void {
    this.listeners = add(this.listeners, listener);
  }

  public removeListener(listener: Fn): void {
    this.listeners = remove(this.listeners, listener);
  }

  public hasListener(listener: Fn): boolean {
    return has(this.listeners, listener);
  }

  public getListenerCount(): number {
    return size(this.listeners);
  }

  public clearListeners(): void {
    this.listeners = undefined;
  }
}

Package Sidebar

Install

npm i adaptive-set

Weekly Downloads

443

Version

0.2.0

License

MIT

Unpacked Size

17.8 kB

Total Files

12

Last publish

Collaborators

  • straybugs