-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathhelpers.ts
55 lines (47 loc) · 1.5 KB
/
helpers.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
import { userInfo, hostname } from 'os';
import * as murmurHash3 from 'murmurhash3js';
import { Context } from './context';
export type FallbackFunction = (name: string, context: Context) => boolean;
export function createFallbackFunction(
name: string,
context: Context,
fallback?: FallbackFunction | boolean,
): Function {
if (typeof fallback === 'function') {
return () => fallback(name, context);
}
if (typeof fallback === 'boolean') {
return () => fallback;
}
return () => false;
}
export function resolveContextValue(context: Context, field: string): string | undefined {
const contextValue = context[field] ?? context.properties?.[field];
return contextValue !== undefined && contextValue !== null ? String(contextValue) : undefined;
}
export function safeName(str: string = '') {
return str.replace(/\//g, '_');
}
export function generateInstanceId(instanceId?: string): string {
if (instanceId) {
return instanceId;
}
let info;
try {
info = userInfo();
} catch (e) {
// unable to read info;
}
const prefix = info
? info.username
: `generated-${Math.round(Math.random() * 1000000)}-${process.pid}`;
return `${prefix}-${hostname()}`;
}
export function generateHashOfConfig(o: Object): string {
const oAsString = JSON.stringify(o);
return murmurHash3.x86.hash128(oAsString);
}
export function getAppliedJitter(jitter: number): number {
const appliedJitter = Math.random() * jitter;
return Math.random() < 0.5 ? -appliedJitter : appliedJitter;
}