summaryrefslogtreecommitdiff
path: root/src/utils.mjs
blob: e0e20a734d3dd7373ba94f029a89df04d91d587d (plain) (blame)
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
export const eq = (a, b) => {
	if (a === b) {
		return true;
	}

	if (a === null || b === null) {
		return false;
	}

	if (typeof a != "object" || typeof b != "object") {
		return false;
	}

	if (Array.isArray(a) !== Array.isArray(b)) {
		return false;
	}

	if (Object.keys(a).length !== Object.keys(b).length) {
		return false;
	}

	for (const k in a) {
		if (!b.hasOwnProperty(k)) {
			return false;
		}
		if (!eq(a[k], b[k])) {
			return false;
		}
	}

	return true;
};

export const keys = (ks, obj) =>
	ks.reduce(
		(ret, k) =>
			obj.hasOwnProperty(k) ?  {...ret, [k]: obj[k]} : ret,
		{},
	);

export const difference = (a, b) => {
	const diff = new Set(a);
	for (const el of b) {
		diff.delete(el);
	}
	return diff;
};

export const assocIn = (obj, path, value) =>
	path.length === 0 ?  obj :
		path.length === 1 ? { ...obj, [path[0]]: value } :
			{
				...obj,
				[path[0]]: assocIn(
					(obj[path[0]] || {}),
					path.slice(1),
					value
				)
			};

export const getIn = (obj, path) =>
	path.length === 0 ? obj :
		getIn(obj?.[path[0]], path.slice(1));

export const first = (arr, fn) => {
	for (const x of arr) {
		const ret = fn(x);
		if (ret) {
			return ret;
		}
	}

	return null;
};

export const log = o => console.error(JSON.stringify(o));