amatiasq
10/11/2019 - 9:56 AM

EcmaScript 2020.js

#!/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?.();