summaryrefslogtreecommitdiffstats
path: root/src/util.ts
blob: 29c707e62b6876ae3b091b9d12be970949ec16f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
export function mapFromObject<T>(obj: {[key: string]: T}): Map<string, T> {
	const ret = new Map();

	for (const k of Object.keys(obj))
		ret.set(k, obj[k]);

	return ret;
}

export function mapValues<K, V1, V2>(f: (v: V1) => V2, map: Map<K, V1>): Map<K, V2> {
	const ret: Map<K, V2> = new Map();

	for (const [k, v] of map)
		ret.set(k, f(v));

	return ret;
}

export async function mapValuesAsync<K, V1, V2>(f: (v: V1) => Promise<V2>, map: Map<K, V1>): Promise<Map<K, V2>> {
	const ret: Map<K, V2> = new Map();

	for (const [k, v] of mapValues(f, map))
		ret.set(k, await v);

	return ret;
}

export function nextPowerOf2(n: number): number {
	let i = 1;

	while (i < n)
		i *= 2;

	return i;
}

export class Listenable<T extends any[]> {
	private readonly listeners: Array<(...args: T) => void> = [];

	public addListener(listener: (...args: T) => void): void {
		this.listeners.push(listener);
	}

	protected runListeners(...args: T): void {
		this.listeners.forEach((l) => l(...args));
	}
}

export function get(url: string): Promise<XMLHttpRequest> {
	return new Promise((resolve, reject) => {
		const xhr = new XMLHttpRequest();

		const handleError = () => {
			if (xhr.readyState !== xhr.DONE) {
				reject(new Error('HTTP request ended in state ' + xhr.readyState));
				return;
			}

			reject(new Error('HTTP request returned status ' + xhr.status));
		};

		xhr.addEventListener('error', handleError);

		xhr.addEventListener('load', () => {
			if (xhr.readyState !== xhr.DONE || xhr.status !== 200) {
				handleError();
				return;
			}

			resolve(xhr);
		});

		xhr.open('GET', url, true);
		xhr.send();
	});
}

export async function getJSON(url: string): Promise<any> {
	return JSON.parse((await get(url)).responseText);
}