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/backend/misc/env-to-number.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2023 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import getLogger from "../logger";
7
8
const L = getLogger("env-to-number").debug;
9
10
// parse environment variable and convert to integer, with fallback if number could not be parsed
11
export function envToInt(name: string, fallback: number) {
12
const value = process.env[name];
13
if (value == null) {
14
L(`envToInt: using fallback value ${fallback} for ${name}`);
15
return fallback;
16
}
17
const parsed = parseInt(value);
18
if (isNaN(parsed)) {
19
L(
20
`envToInt: could not parse ${name}=${value}, using fallback value ${fallback}`
21
);
22
return fallback;
23
}
24
return parsed;
25
}
26
27
// parse environment variable and convert to float, with fallback if number could not be parsed
28
export function envToFloat(name: string, fallback: number) {
29
const value = process.env[name];
30
if (value == null) {
31
L(`envToFloat: using fallback value ${fallback} for ${name}`);
32
return fallback;
33
}
34
const parsed = parseFloat(value);
35
if (isNaN(parsed)) {
36
L(
37
`envToFloat: could not parse ${name}=${value}, using fallback value ${fallback}`
38
);
39
return fallback;
40
}
41
return parsed;
42
}
43
44