Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Readme

disposable: wrapper to make an object disposable with the using keyword

using feature explanation in TypeScript 5.2 docs

Example:

import { disposable } from "https://esm.town/v/postpostscript/disposable"; using state = disposable( { x: 1, y: 2, }, (value) => console.log("state disposed", value), ); // state disposed { x: 1, y: 2, [Symbol(Symbol.dispose)]: [Function (anonymous)] }

or, to use a proxy instead of modifying the original object:

using state = disposable( { x: 1, y: 2, }, (value) => console.log("proxyState disposed", value), true, ); // proxyState disposed { x: 1, y: 2 }

Full Example

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
export function disposable<T extends object>(
value: T,
onDispose: (value: T) => void,
proxy = false,
): T {
const dispose = async () => {
if (proxy && value[Symbol.dispose]) {
await value[Symbol.dispose]();
}
return onDispose(value);
};
if (!proxy) {
value[Symbol.dispose] = dispose;
return value;
}
return new Proxy(value, {
get(target, key, receiver) {
if (key === Symbol.dispose) {
return dispose;
}
return Reflect.get(target, key, receiver);
},
});
}
April 24, 2024