CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/util/maps.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { reduce } from "lodash";
7
import { is_array, is_object } from "./type-checking";
8
9
// compare the values in a map a by the values of b
10
// or just by b if b is a number, using func(a, b)
11
function map_comp_fn(func, fallback) {
12
return (a, b) => {
13
const c = {};
14
if (typeof b === "number") {
15
for (let k in a) {
16
let v = a[k];
17
c[k] = func(v, b);
18
}
19
} else {
20
for (let k in a) {
21
let v = a[k];
22
c[k] = func(v, b[k] ?? fallback);
23
}
24
}
25
return c;
26
};
27
}
28
29
export const map_limit = map_comp_fn(Math.min, Number.MAX_VALUE);
30
export const map_min = map_limit;
31
export const map_max = map_comp_fn(Math.max, Number.MIN_VALUE);
32
33
// arithmetic sum of an array
34
export function sum(arr, start = 0) {
35
if (start == null) {
36
start = 0;
37
}
38
return reduce(arr, (a, b) => a + b, start);
39
}
40
41
// returns true if the given map is undefined or empty, or all the values are falsy
42
export function is_zero_map(map: undefined | null | object): boolean {
43
if (map == null) {
44
return true;
45
}
46
for (let k in map) {
47
if (map[k]) {
48
return false;
49
}
50
}
51
return true;
52
}
53
54
// Returns copy of map with no undefined/null values (recursive).
55
// Doesn't modify map. If map is an array, just returns it
56
// with no change even if it has undefined values.
57
export function map_without_undefined_and_null(map?: object): object | undefined | null {
58
if (map == null) {
59
return;
60
}
61
if (is_array(map)) {
62
return map;
63
}
64
const new_map = {};
65
for (let k in map) {
66
const v = map[k];
67
if (v == null) {
68
continue;
69
} else {
70
new_map[k] = is_object(v) ? map_without_undefined_and_null(v) : v;
71
}
72
}
73
return new_map;
74
}
75
76
// modify map in places deleting keys with null or undefined
77
// values; NOT recursive.
78
export function map_mutate_out_undefined_and_null(map: object): void {
79
for (let k in map) {
80
const v = map[k];
81
if (v == null) {
82
delete map[k];
83
}
84
}
85
}
86
87