UNPKG

2.44 kBtext/coffeescriptView Raw
1
2Utils = require './Utils'
3Inline = require './Inline'
4
5# Dumper dumps JavaScript variables to YAML strings.
6#
7class Dumper
8
9 # The amount of spaces to use for indentation of nested nodes.
10 @indentation: 4
11
12
13 # Dumps a JavaScript value to YAML.
14 #
15 # @param [Object] input The JavaScript value
16 # @param [Integer] inline The level where you switch to inline YAML
17 # @param [Integer] indent The level of indentation (used internally)
18 # @param [Boolean] exceptionOnInvalidType true if an exception must be thrown on invalid types (a JavaScript resource or object), false otherwise
19 # @param [Function] objectEncoder A function to serialize custom objects, null otherwise
20 #
21 # @return [String] The YAML representation of the JavaScript value
22 #
23 dump: (input, inline = 0, indent = 0, exceptionOnInvalidType = false, objectEncoder = null) ->
24 output = ''
25 prefix = (if indent then Utils.strRepeat(' ', indent) else '')
26
27 if inline <= 0 or typeof(input) isnt 'object' or input instanceof Date or Utils.isEmpty(input)
28 output += prefix + Inline.dump(input, exceptionOnInvalidType, objectEncoder)
29
30 else
31 if input instanceof Array
32 for value in input
33 willBeInlined = (inline - 1 <= 0 or typeof(value) isnt 'object' or Utils.isEmpty(value))
34
35 output +=
36 prefix +
37 '-' +
38 (if willBeInlined then ' ' else "\n") +
39 @dump(value, inline - 1, (if willBeInlined then 0 else indent + @indentation), exceptionOnInvalidType, objectEncoder) +
40 (if willBeInlined then "\n" else '')
41
42 else
43 for key, value of input
44 willBeInlined = (inline - 1 <= 0 or typeof(value) isnt 'object' or Utils.isEmpty(value))
45
46 output +=
47 prefix +
48 Inline.dump(key, exceptionOnInvalidType, objectEncoder) + ':' +
49 (if willBeInlined then ' ' else "\n") +
50 @dump(value, inline - 1, (if willBeInlined then 0 else indent + @indentation), exceptionOnInvalidType, objectEncoder) +
51 (if willBeInlined then "\n" else '')
52
53 return output
54
55
56module.exports = Dumper