xref: /aosp_15_r20/external/pigweed/pw_ide/ts/pigweed-vscode/src/disposables.ts (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1// Copyright 2024 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15interface IDisposable {
16  dispose: () => void;
17}
18
19export class Disposable implements IDisposable {
20  disposables: IDisposable[] = [];
21
22  dispose = () => {
23    this.disposables.forEach((it) => it.dispose());
24  };
25}
26
27export class Disposer extends Disposable {
28  add = <T extends IDisposable>(disposable: T): T => {
29    this.disposables.push(disposable);
30    return disposable;
31  };
32
33  addMany = <T extends Record<string, IDisposable>>(disposables: T): T => {
34    this.disposables.push(...Object.values(disposables));
35    return disposables;
36  };
37}
38