All files / src/collections utils.ts

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

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                        69x       29x 26x 26x 23x 23x 23x 37x       3x              
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>(),
      batchTask_: () => {
        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,
  );
}