/
index.ts
122 lines (101 loc) · 2.66 KB
/
index.ts
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import debounce from 'lodash.debounce'
import throttle from 'lodash.throttle'
import deepMerge from 'deepmerge'
import deepClone from 'clone-deep'
import { CompareResult } from './types'
export * from './types'
export * from './dom'
export * from './svg'
// Re-exports from other libraries.
export { debounce, throttle, deepMerge, deepClone }
/**
* For use with Array#sort as the default comparator converts to
* strings beforehand.
*
* Reference:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
*/
export function compareFunc(a: number, b: number): CompareResult {
if (a < b) {
return -1
}
if (a > b) {
return 1
}
return 0
}
/**
* Constrains a number between {@param min} and {@param max}.
*
* @param min
* @param max
*/
export function constrain(a: number, min: number, max?: number): number {
if (a < min) {
return min
}
if (max != null && a > max) {
return max
}
return a
}
/**
* In some cases, it is useful at runtime to know if
* we're inside of a Jest environment.
*/
export function getIsJest() {
return process.env.JEST_WORKER_ID !== undefined
}
/**
* Using JSON.parse and JSON.stringify to clone a JS object.
*/
export function jsonClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj))
}
const BASE_10 = 10
/**
* Rounds a number to a fixed set of decimal places.
*/
export function roundFixed(a: number, places: number = 0, base: number = BASE_10): number {
const factor = Math.pow(base, places)
return Math.round(a * factor) / factor
}
/**
* Removes any subdomains from the host.
*
* Example: abc.google.com -> google.com
*/
export function getRootHostname(hostname: string, baseParts: number = 2): string {
const parts = hostname.split('.')
if (parts.length <= baseParts) {
return hostname
}
return parts.slice(-baseParts).join('.')
}
/**
* Simple implementation of the invariant pattern (used by Facebook).
*/
export function invariant(condition: boolean, message: string) {
if (!condition) {
if (__DEV__) {
throw new Error(message)
} else {
throw new Error('Invariant Error')
}
}
}
/**
* Resolves the Promise after {@param duration}.
*/
export function resolveTimeout(duration: number = 0): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, duration))
}
/**
* Resolve on next idle callback.
*/
export function resolveIdleCallback(): Promise<void> {
if (typeof requestIdleCallback !== 'undefined') {
return new Promise((resolve) => requestIdleCallback(() => resolve()))
}
return resolveTimeout(1)
}