Algorithms#

Most algorithmic work uses methods on arrays and other built-in collections.

Sorting#

const xs = [5, 1, 4, 2, 3];
xs.sort((a, b) => a - b);              // ascending
xs.sort((a, b) => b - a);              // descending

people.sort((a, b) => a.age - b.age);

Map / Filter / Reduce#

const total = xs
    .filter((x) => x > 0)
    .map((x) => x * x)
    .reduce((acc, x) => acc + x, 0);

Recursion#

function fact(n: number): number {
    return n <= 1 ? 1 : n * fact(n - 1);
}

Async#

Coordinate concurrent work with Promise.all and async / await:

async function fetchAll(urls: string[]): Promise<string[]> {
    const responses = await Promise.all(urls.map((u) => fetch(u)));
    return Promise.all(responses.map((r) => r.text()));
}