Listings Roden/ECMAScript

Listing 1: Umständlicher Code zum Auslesen einer Datei
const fs = require('fs');

const getHosts = function (callback) {
    fs.readFile('/etc/hosts', 'utf8', (err, data) => {
      if (err) {
        return callback(err);
      }

      callback(null, data);
    });
};

-------

Listing 2: Vereinfachter Code zum Auslesen einer Datei
const fs = require('fs');

const getHosts = async function () {
    const data = await fs.promises.readFile('/etc/hosts', 'utf8');

    return data;
};

-------

Listing 3: Strings mithilfe der Funktion padStart mit Zeichen füllen
const prices = [
    '23.95',
    '42.95',
    '7.99'
];

for (const price of prices) {
    console.log(price.padStart(10));
}

-------

Listing 4: Die Funktion Object.entries gibt Werte als Arrays zurück
const colors = {
    red: '#ff0000',
    green: '#00ff00',
    blue: '#0000ff'
};

for (const [ name, code ] of Object.entries(colors)) {
    console.log(`${name}: ${code}`);
}

-------

Listing 5: Objekte mit dem Spread-Operator kopieren
const source = {
    value: 23,
    otherValue: 42,
};

const target = {
    ...source,
    additionalValue: 7
};

-------

Listing 6: catch funktioniert auch ohne Fehlerbindung
const isInstalled = function (name) {
    try {
      require(name);

      return true;
    } catch {
      return false;
    }
}

-------

Listing 7: Object.fromEntries ermöglicht map, filter und reduce auf Objekten
const versions = {
    node: '10.16.0',
    npm: '6.10.2',
    express: '4.17.1'
};

const filteredVersions = Object.fromEntries(
    Object.entries(versions).
      filter(([ key, value ]) => key.startsWith('n'))
);

console.log(filteredVersions);

// => {
//        node: '10.16.0',
//        npm: '6.10.2'
//      }

-------

Listing 8: Das Ergebnis der Addition ist nicht mehr zu unterscheiden
const value1 = Number.MAX_SAFE_INTEGER + 1;
const value2 = Number.MAX_SAFE_INTEGER + 2;

console.log(value1);
// => 9007199254740992

console.log(value2);
// => 9007199254740992

-------

Listing 9: Algorithmus zum Berechnen von Primzahlen
const isPrime = function (p) {
    for (let i = 2n; i * i <= p; i++) {
      if (p % i === 0n) {
        return false;
      }
    }

    return true;
};

-------

Listing 10: Die Funktion mit self, window und global
const getGlobal = function () {
    if (typeof self !== 'undefined') {
      return self;
    }
    if (typeof window !== 'undefined') {
      return window;
    }
    if (typeof global !== 'undefined') {
      return global;
    }

    throw new Error('Failed to get global context.');
};

-------

Listing 11: Das #-Zeichen markiert private Elemente
class Stack {
    constructor () {
      this.#data = [];
    }

    push (value) {
      this.#data.push(value);
    }

    // ...
}