-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathjavascript_snippet_syntax.ts
66 lines (58 loc) · 2.08 KB
/
javascript_snippet_syntax.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
import { GeneratedExpression } from '@cucumber/cucumber-expressions'
import {
ISnippetSnytax,
ISnippetSyntaxBuildOptions,
SnippetInterface,
} from './snippet_syntax'
const CALLBACK_NAME = 'callback'
export default class JavaScriptSnippetSyntax implements ISnippetSnytax {
private readonly snippetInterface: SnippetInterface
constructor(snippetInterface: SnippetInterface) {
this.snippetInterface = snippetInterface
}
build({
comment,
generatedExpressions,
functionName,
stepParameterNames,
}: ISnippetSyntaxBuildOptions): string {
let functionKeyword = 'function '
if (this.snippetInterface === SnippetInterface.AsyncAwait) {
functionKeyword = 'async ' + functionKeyword
}
let implementation: string
if (this.snippetInterface === SnippetInterface.Callback) {
implementation = `${CALLBACK_NAME}(null, 'pending');`
} else if (this.snippetInterface === SnippetInterface.Promise) {
implementation = "return Promise.resolve('pending');"
} else {
implementation = "return 'pending';"
}
const definitionChoices = generatedExpressions.map(
(generatedExpression, index) => {
const prefix = index === 0 ? '' : '// '
const allParameterNames =
generatedExpression.parameterNames.concat(stepParameterNames)
if (this.snippetInterface === SnippetInterface.Callback) {
allParameterNames.push(CALLBACK_NAME)
}
return `${prefix + functionName}('${this.escapeSpecialCharacters(
generatedExpression
)}', ${functionKeyword}(${allParameterNames.join(', ')}) {\n`
}
)
return (
`${definitionChoices.join('')} // ${comment}\n` +
` ${implementation}\n` +
'});'
)
}
private escapeSpecialCharacters(generatedExpression: GeneratedExpression) {
let source = generatedExpression.source
// double up any backslashes because we're in a javascript string
source = source.replace(/\\/g, '\\\\')
// escape any single quotes because that's our quote delimiter
source = source.replace(/'/g, "\\'")
return source
}
}