forked from Kong/httpsnippet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.ts
More file actions
92 lines (83 loc) · 2.57 KB
/
helpers.ts
File metadata and controls
92 lines (83 loc) · 2.57 KB
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
/**
* Create an string of given length filled with blank spaces
*
* @param length Length of the array to return
* @param str String to pad out with
*/
function buildString(length: number, str: string) {
return str.repeat(length);
}
/**
* Create a string corresponding to a Dictionary or Array literal representation with pretty option
* and indentation.
*/
function concatValues(
concatType: 'array' | 'object',
values: any,
pretty: boolean,
indentation: string,
indentLevel: number,
) {
const currentIndent = buildString(indentLevel, indentation);
const closingBraceIndent = buildString(indentLevel - 1, indentation);
const join = pretty ? `,\n${currentIndent}` : ', ';
const openingBrace = concatType === 'object' ? '{' : '[';
const closingBrace = concatType === 'object' ? '}' : ']';
if (pretty) {
return `${openingBrace}\n${currentIndent}${values.join(
join,
)}\n${closingBraceIndent}${closingBrace}`;
}
return openingBrace + values.join(join) + closingBrace;
}
/**
* Create a valid Python string of a literal value according to its type.
*
* @param {*} value Any JavaScript literal
* @param {Object} opts Target options
* @return {string}
*/
export const literalRepresentation = (
value: any,
opts: Record<string, any>,
indentLevel?: number,
): any => {
indentLevel = indentLevel === undefined ? 1 : indentLevel + 1;
switch (Object.prototype.toString.call(value)) {
case '[object Number]':
return value;
case '[object Array]': {
let pretty = false;
const valuesRepresentation: any = (value as any[]).map(v => {
// Switch to prettify if the value is a dictionary with multiple keys
if (Object.prototype.toString.call(v) === '[object Object]') {
pretty = Object.keys(v).length > 1;
}
return literalRepresentation(v, opts, indentLevel);
});
return concatValues('array', valuesRepresentation, pretty, opts.indent, indentLevel);
}
case '[object Object]': {
const keyValuePairs = [];
for (const key in value) {
keyValuePairs.push(`"${key}": ${literalRepresentation(value[key], opts, indentLevel)}`);
}
return concatValues(
'object',
keyValuePairs,
opts.pretty && keyValuePairs.length > 1,
opts.indent,
indentLevel,
);
}
case '[object Null]':
return 'None';
case '[object Boolean]':
return value ? 'True' : 'False';
default:
if (value === null || value === undefined) {
return '';
}
return `"${value.toString().replace(/"/g, '\\"')}"`;
}
};