stringify.js 831 B

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. var test = require('tape');
  3. var traverse = require('../');
  4. test('stringify', function (t) {
  5. var obj = [5, 6, -3, [7, 8, -2, 1], { f: 10, g: -13 }];
  6. var s = '';
  7. traverse(obj).forEach(function (node) {
  8. if (Array.isArray(node)) {
  9. this.before(function () { s += '['; });
  10. this.post(function (child) {
  11. if (!child.isLast) { s += ','; }
  12. });
  13. this.after(function () { s += ']'; });
  14. } else if (typeof node === 'object') {
  15. this.before(function () { s += '{'; });
  16. this.pre(function (x, key) {
  17. s += '"' + key + '":';
  18. });
  19. this.post(function (child) {
  20. if (!child.isLast) { s += ','; }
  21. });
  22. this.after(function () { s += '}'; });
  23. } else if (typeof node === 'function') {
  24. s += 'null';
  25. } else {
  26. s += node.toString();
  27. }
  28. });
  29. t.equal(s, JSON.stringify(obj));
  30. t.end();
  31. });