-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathutils.ts
89 lines (79 loc) · 2.28 KB
/
utils.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
import { type editor, MarkerSeverity, Uri } from 'monaco-editor'
import environment from '~/environment'
const segmentLength = 'time.Now()'.length
const issueUrl = Uri.parse(`${environment.urls.github}/issues/104`)
const timeNowUsageWarning =
'Warning: `time.Now()` will always return fake time. ' +
'Change current environment to WebAssembly to use real date and time.'
/**
* Checks if passed source code contains `time.Now()` calls and returns
* a list of warning markers for those calls.
*
* Returns empty array if no calls found.
* @param code
* @param editorInstance
*/
export const getTimeNowUsageMarkers = (
code: string,
editorInstance: editor.IStandaloneCodeEditor,
): editor.IMarkerData[] => {
const regex = /\W(time\.Now\(\))/gm
const matches: number[] = []
let match: RegExpExecArray | null
while ((match = regex.exec(code))) {
matches.push(match.index)
}
if (matches.length === 0) {
return []
}
const model = editorInstance.getModel()!
return matches.map((index) => {
// Skip extra character or white-space before expression
const { lineNumber, column } = model.getPositionAt(index + 1)
return {
code: {
value: 'More information',
target: issueUrl,
},
severity: MarkerSeverity.Warning,
message: timeNowUsageWarning,
startLineNumber: lineNumber,
endLineNumber: lineNumber,
startColumn: column,
endColumn: column + segmentLength,
}
})
}
/**
* Wraps async function with debounce timer.
*
* @param fn Function
* @param delay Debounce time
*/
export const asyncDebounce = <T>(fn: (...args) => Promise<T>, delay: number) => {
let lastTimeoutId: NodeJS.Timeout | null = null
return async (...args) => {
if (lastTimeoutId) {
clearTimeout(lastTimeoutId)
}
return await new Promise<T>((resolve, reject) => {
lastTimeoutId = setTimeout(() => {
fn(...args)
.then(resolve)
.catch(reject)
}, delay)
})
}
}
/**
* Wraps passed function with a debouncer
*/
export const debounce = <T>(fn: (...args) => T, delay: number) => {
let lastTimeoutId: NodeJS.Timeout | null = null
return (...args) => {
if (lastTimeoutId) {
clearTimeout(lastTimeoutId)
}
lastTimeoutId = setTimeout(() => fn(...args), delay)
}
}