All files / src/collections utils.ts

100% Statements 25/25
100% Branches 6/6
100% Functions 2/2
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34  2x             2x   64x 64x 64x 64x 64x 64x 25x 22x 22x 21x 21x 21x 35x 35x 21x 25x 3x 3x 25x 64x 64x 64x 64x  
import { type BatchTask } from "../batch";
import { on, type RemoveListener, send, size, type EventObject } from "../event";
 
/** When a value should be disposed */
export interface OnDisposeValue<V> extends BatchTask<EventObject<V>> {
  readonly delete_: Set<V>;
}
 
export function onDisposeValue<V>(
  this: { onDisposeValue_?: null | OnDisposeValue<V> },
  fn: (value: V) => void,
): RemoveListener {
  return on(
    (this.onDisposeValue_ ??= {
      delete_: new Set<V>(),
      task_: () => {
        if (this.onDisposeValue_ && size(this.onDisposeValue_)) {
          const { delete_ } = this.onDisposeValue_;
          if (delete_.size) {
            const removedValues = [...delete_];
            delete_.clear();
            for (const value of removedValues) {
              send(this.onDisposeValue_, value);
            }
          }
        } else {
          this.onDisposeValue_ = null;
        }
      },
    }),
    fn,
  );
}