UNPKG

2.64 kBJavaScriptView Raw
1/*
2 * Copyright 2020 Palantir Technologies, Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16import { CLAMP_MIN_MAX } from "../errors";
17/** Returns whether bundler-injected variable `NODE_ENV` equals `env`. */
18export function isNodeEnv(env) {
19 return typeof NODE_ENV !== "undefined" && NODE_ENV === env;
20}
21/**
22 * Returns the difference in length between two arrays. A `null` argument is
23 * considered an empty list. The return value will be positive if `a` is longer
24 * than `b`, negative if the opposite is true, and zero if their lengths are
25 * equal.
26 */
27export function arrayLengthCompare(a, b) {
28 if (a === void 0) { a = []; }
29 if (b === void 0) { b = []; }
30 return a.length - b.length;
31}
32/**
33 * Returns true if the two numbers are within the given tolerance of each other.
34 * This is useful to correct for floating point precision issues, less useful
35 * for integers.
36 */
37export function approxEqual(a, b, tolerance) {
38 if (tolerance === void 0) { tolerance = 0.00001; }
39 return Math.abs(a - b) <= tolerance;
40}
41/**
42 * Clamps the given number between min and max values. Returns value if within
43 * range, or closest bound.
44 */
45export function clamp(val, min, max) {
46 if (val == null) {
47 return val;
48 }
49 if (max < min) {
50 throw new Error(CLAMP_MIN_MAX);
51 }
52 return Math.min(Math.max(val, min), max);
53}
54/** Returns the number of decimal places in the given number. */
55export function countDecimalPlaces(num) {
56 if (!isFinite(num)) {
57 return 0;
58 }
59 var e = 1;
60 var p = 0;
61 while (Math.round(num * e) / e !== num) {
62 e *= 10;
63 p++;
64 }
65 return p;
66}
67var uniqueCountForNamespace = new Map();
68/** Generate a unique ID within a given namespace, using a simple counter-based implementation to avoid collisions. */
69export function uniqueId(namespace) {
70 var _a;
71 var curCount = (_a = uniqueCountForNamespace.get(namespace)) !== null && _a !== void 0 ? _a : 0;
72 uniqueCountForNamespace.set(namespace, curCount + 1);
73 return "".concat(namespace, "-").concat(curCount);
74}
75//# sourceMappingURL=jsUtils.js.map
\No newline at end of file