Javascript/Typescript Cheatsheet
Resources
References:
- MDN Web Docs - Javascript
(developer.mozilla.org)
- TypeScript Documentation
(www.typescriptlang.org)
- Learn X in Y minutes - Javascript
(learnxinyminutes.com)
- Learn X in Y minutes - Typescript
(learnxinyminutes.com)
Others:
- TS Playground
(www.typescriptlang.org)
General
throw new Error("your message here");
Common Types
Object
MDN Web Docs - Object
MDN Web Docs - Enumerability and ownership of properties
for (const [k, v] of Object.entries(obj)) console.log(`${k}: ${v}`);
for (const k of Object.keys(obj)) console.log(k);
for (const v of Object.values(obj)) console.log(v);
// .fromEntries() and .entries() are inverses of each other. Useful for object transforms:
const obj2 = Object.fromEntries(
Object.entries(obj1).map(([k, v]) => [k, v * 2]),
);
Object.assign(dst, src) // Copies all enumerable own properties from src to dst. Returns dst.
// TODO: Write notes about the spread operator.
Array
arr.length
for (const x of arr) console.log(x);
for (const [i, v] of arr.entries()) console.log(`${i}: ${v}`);
arr.forEach((x, i, originalArray) => console.log(x))
[v1, v2, ...arr1, ...arr2]
[v1, v2, ...(condition ? [v3] : [])]
// Push/pop/peek at the back
arr.push(...values)
arr.pop()
arr.at(-1)
// Push/pop/peek at the front
arr.unshift(...values)
arr.shift()
arr[0]
arr.slice(startInclusive, endExclusive) // Returns a new array
arr.join(", ") // ["foo", "bar", "baz"] --> "foo, bar, baz"
arr.map((x) => x * 2) // Returns a new array
arr.reduce((acc, curr, index) => acc + curr, initialValue) // aka fold/accumulate. Use .reduceRight() for reverse iteration
arr.filter((x) => x > 0) // Returns a new array of values for which the predicate is true
arr.every((x) => x > 0) // true if all values are true
arr.some((x) => x > 0) // true if at least one value is true
Array.isArray(x) // Returns boolean. Unfortunately type-narrows to any[].
// This is a known limitation with TS: <https://github.com/microsoft/TypeScript/issues/17002>
arr.sort() // THIS WILL ALWAYS SORT BY IMPLICIT STRING CONVERSION
arr.sort((a, b) => b - a)
Map
The associative array ADT, also known as a dictionary in Python.
// Constructor takes any iterable with key-value pairs
const map = new Map([
[k1, v1],
[k2, v2],
[k3, v3],
]);
map.size
for (const [k, v] of map) console.log(`${k}: ${v}`);
map.forEach((v, k, originalMap) => console.log(`${k}: ${v}`)); // (v, k) is not a typo.
map.set(key, value) // Returns the same map
map.delete(key) // Returns true if key was in the map, false otherwise
map.clear() // Returns undefined
map.get(key)
map.has(key) // true if key is a key in the map
Set
const set = new Set([x1, x2, x3]);
set.size
for (const x of set) console.log(x);
set.forEach((x, _, originalSet) => console.log(x)) // Second param is always the same as the first.
set.add(value) // Returns the same set
set.delete(value) // Returns true if value was in the set, false otherwise
set.clear() // Returns undefined
set.has(value) // true if value is in set
The Module System
import foobar from "mymodule";
Basic Recipes (JS Only)
Max Heap
function heapify(heap) {
for (let i = (heap.length >> 1) - 1; i >= 0; --i) {
_downHeapify(heap, i);
}
}
function hpush(heap, item) {
let curr = heap.length;
heap.push(item);
_upHeapify(heap, curr);
}
// Assumes heap.length > 0
function hpop(heap) {
if (heap.length === 1) return heap.pop();
const toReturn = heap[0];
heap[0] = heap.pop();
_downHeapify(heap, 0);
return toReturn;
}
// Assumes heap.length > 0
function hpushpop(heap, item) {
if (item[0] < heap[0][0]) {
[item, heap[0]] = [heap[0], item];
_downHeapify(heap, 0);
}
return item;
}
function hpopManyWithoutKey(heap, n) {
const toReturn = new Array(n);
for (let i = 1; i < n; ++i) {
toReturn[i] = heap[0][1];
heap[0] = heap.pop();
_downHeapify(heap, 0);
}
toReturn[0] = heap[0][1];
return toReturn;
}
function hpopManyWithoutReturn(heap, n) {
if (heap.length === n) {
heap.splice(0, heap.length);
} else {
for (let i = 1; i < n; ++i) {
heap[0] = heap.pop();
_downHeapify(heap, 0);
}
heap[0] = heap.pop();
}
}
function _downHeapify(heap, i) {
const left = (i << 1) + 1;
if (heap[left] === undefined) return;
const right = left + 1;
const next = (heap[right] === undefined || heap[left][0] > heap[right][0]) ? left : right;
if (heap[next][0] <= heap[i][0]) return;
[heap[next], heap[i]] = [heap[i], heap[next]];
_downHeapify(heap, next);
}
function _upHeapify(heap, i) {
if (i === 0) return;
const parent = (i - 1) >> 1;
if (heap[parent][0] > heap[i][0]) return;
[heap[parent], heap[i]] = [heap[i], heap[parent]];
_upHeapify(heap, parent);
}
TODO
Things I think I should add notes on some time:
- Object spread operators
- Prototype inheritance system
- OOP
Other TODOs:
- I’m actually not sure what
hpopManyWithoutKey()
does at a glance, and I’m actually still confused even as I look at it.