(value: unknown, language: 'javascript' | 'python')
| 14 | * formatLiteralForCode({a: 1}, 'python') // => "json.loads('{\"a\":1}')" |
| 15 | */ |
| 16 | export function formatLiteralForCode(value: unknown, language: 'javascript' | 'python'): string { |
| 17 | const isPython = language === 'python' |
| 18 | |
| 19 | if (value === undefined) { |
| 20 | return isPython ? 'None' : 'undefined' |
| 21 | } |
| 22 | if (value === null) { |
| 23 | return isPython ? 'None' : 'null' |
| 24 | } |
| 25 | if (typeof value === 'boolean') { |
| 26 | return isPython ? (value ? 'True' : 'False') : String(value) |
| 27 | } |
| 28 | if (typeof value === 'number') { |
| 29 | if (Number.isNaN(value)) { |
| 30 | return isPython ? "float('nan')" : 'NaN' |
| 31 | } |
| 32 | if (value === Number.POSITIVE_INFINITY) { |
| 33 | return isPython ? "float('inf')" : 'Infinity' |
| 34 | } |
| 35 | if (value === Number.NEGATIVE_INFINITY) { |
| 36 | return isPython ? "float('-inf')" : '-Infinity' |
| 37 | } |
| 38 | return String(value) |
| 39 | } |
| 40 | if (typeof value === 'string') { |
| 41 | return JSON.stringify(value) |
| 42 | } |
| 43 | // Objects and arrays - Python needs json.loads() because JSON true/false/null aren't valid Python |
| 44 | if (isPython) { |
| 45 | return `json.loads(${JSON.stringify(JSON.stringify(value))})` |
| 46 | } |
| 47 | return JSON.stringify(value) |
| 48 | } |
no outgoing calls
no test coverage detected