Skip to content

Commit

Permalink
feat: add pretty-printing options
Browse files Browse the repository at this point in the history
Closes #35
  • Loading branch information
dmbaturin authored and kenany committed Mar 3, 2021
1 parent 6f7fa33 commit 786a664
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 3 deletions.
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,24 @@ var json2toml = require('json2toml');

json2toml({simple: true});
// => 'simple = true\n'

// Also supports pretty-printing options
json2toml(
{
deeply: {
option: false,
nested: {
option: true
}
}
},
{ indent: 2, newlineAfterSection: true }
);
// => [deeply]
// => option = false
// =>
// => [deeply.nested]
// => option = true
```

## Installation
Expand All @@ -23,6 +41,10 @@ $ npm install json2toml
var json2toml = require('json2toml');
```

### json2toml(hash)
### json2toml(hash, options = {})

Converts an _Object_ `hash` to TOML, and returns the result as a _String_.

- `options.indent`: Number of spaces for indentation.
- `options.newlineAfterSection`: Whether or not to output a newline after the
last pair in a hash if that hash wasn't empty.
11 changes: 9 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,34 @@ function format(obj) {
: JSON.stringify(obj);
}

module.exports = function(hash) {
module.exports = function(hash, options = {}) {
function visit(hash, prefix) {
var nestedPairs = [];
var simplePairs = [];

var indentStr = '';

forEach(keys(hash).sort(), function(key) {
var value = hash[key];
(isPlainObject(value) ? nestedPairs : simplePairs).push([key, value]);
});

if (!(isEmpty(prefix) || isEmpty(simplePairs))) {
toml += '[' + prefix + ']\n';
indentStr = ''.padStart(options.indent, ' ');
}

forEach(simplePairs, function(array) {
var key = array[0];
var value = array[1];

toml += key + ' = ' + format(value) + '\n';
toml += indentStr + key + ' = ' + format(value) + '\n';
});

if (!isEmpty(simplePairs) && options.newlineAfterSection) {
toml += '\n';
}

forEach(nestedPairs, function(array) {
var key = array[0];
var value = array[1];
Expand Down
12 changes: 12 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,15 @@ test('nested', function(t) {
+ 'again = "it never ends"\n';
t.equal(json2toml(hash), toml);
});

test('pretty', function(t) {
t.plan(1);

var hash = { nested: { hash: { deep: true } } };
var toml = '[nested.hash]\n deep = true';

t.equal(
json2toml(hash, { indent: 2, newlineAfterSection: true }).trim(),
toml
);
});

0 comments on commit 786a664

Please sign in to comment.