Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Last active February 24, 2021 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amatiasq/64825af83547af987129a0a6ee82d70f to your computer and use it in GitHub Desktop.
Save amatiasq/64825af83547af987129a0a6ee82d70f to your computer and use it in GitHub Desktop.
EcmaScript
#!/usr/bin/env node
const meUrl = import.meta.url;
const icon = await fetch(new URL('./icon.png', meUrl));
const element = import.meta.scriptElement ?? { remove() {} };
element.remove();
// Fields & privates
class MyCounter {
#count = 0;
get count() {
return this.#count;
}
increase() {
this.#modify(1);
}
decrease() {
this.#modify(-1);
}
#modify(modifier) {
this.#count += modifier;
}
}
const counter = new MyCounter();
counter.increase();
if (counter.count === 1_000_000) {
console.error('WTF!');
}
// WeakRefs and "destructors"
const filesFinalization = new FinalizationGroup(holdings => {
for (const file of holdings) {
console.log(`File leaked: ${file}`);
}
});
class MyFile {
#file;
constructor(path) {
this.#file = new File(path);
const holding = this.#file;
filesFinalization.register(this, holding, this);
}
close() {
filesFinalization.unregister(this);
File.close(this.#file);
}
}
const myMap = new Map();
for (let i = 0; i < 100; i++) {
myMap.set(i, new WeakRef(new MyFile(meUrl)));
}
// optional chaining
// const a = myMap.get(0);
// if (a) a.close();
myMap.get(0)?.close();
let myFunc = () => null;
myFunc = null;
myFunc?.();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment