All files / src/impl AutoCloseMany.impl.ts

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

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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 5525x   25x                   25x 169x                     177x       146x 146x 151x 151x   1x     146x 1x         4x       169x             169x  
import { AutoClose, AutoCloseMany, AutoCloseType, typeToAutoClose } from "@jonloucks/contracts-ts/api/AutoClose";
import { RequiredType } from "@jonloucks/contracts-ts/api/Types";
import { Internal } from "./Internal.impl";
 
export { AutoCloseMany } from "@jonloucks/contracts-ts/api/AutoClose";
export { RequiredType } from "@jonloucks/contracts-ts/api/Types";
 
/**
 * Create an AutoCloseMany instance.
 *
 * @returns the AutoCloseMany implementation
 */
export function create(): RequiredType<AutoCloseMany> {
  return AutoCloseManyImpl.internalCreate();
}
 
// ---- Implementation details below ----
 
/**
 * AutoCloseMany implementation.
 */
class AutoCloseManyImpl implements AutoCloseMany {
 
  add(closeable: RequiredType<AutoCloseType>): void {
    this.#closeables.push(typeToAutoClose(closeable));
  }
 
  close(): void {
    const errorList: unknown[] = [];
    while (this.#closeables.length > 0) {
      try {
        this.#closeables.pop()?.close();
      } catch (error) {
        errorList.push(error);
      }
    }
    if (errorList.length > 0) {
      Internal.throwAggregateError("Multiple while closing.", ...errorList);
    }
  }
 
  [Symbol.dispose](): void {
    this.close();
  }
 
  static internalCreate(): RequiredType<AutoCloseMany> {
    return new AutoCloseManyImpl();
  }
 
  private constructor() {
  }
 
 
  readonly #closeables: RequiredType<AutoClose>[] = [];
};