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);
Search#
Linear search.
const i = xs.indexOf(target);
const found = xs.find((x) => x.name === "operator");
Binary search on a sorted array.
function binarySearch(xs: number[], target: number): number {
let lo = 0, hi = xs.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (xs[mid] === target) return mid;
if (xs[mid] < target) lo = mid + 1;
else hi = mid;
}
return -1;
}
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()));
}