From 668352964878c1f896b3f57b69a989717c0fae5c Mon Sep 17 00:00:00 2001 From: James Halliday Date: Sat, 4 Sep 2010 04:00:16 -0800 Subject: [PATCH] add stringify to examples --- examples/stringify.js | 35 +++++++++++++++++++++++++++++++++++ test/stringify.js | 3 +-- 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100755 examples/stringify.js diff --git a/examples/stringify.js b/examples/stringify.js new file mode 100755 index 0000000..7148e95 --- /dev/null +++ b/examples/stringify.js @@ -0,0 +1,35 @@ +#!/usr/bin/env node +var Traverse = require('traverse'); +var sys = require('sys'); + +var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; + +var s = ''; +Traverse(obj).forEach(function (node) { + if (Array.isArray(node)) { + this.before(function () { s += '[' }); + this.post(function (child) { + if (!child.isLast) s += ','; + }); + this.after(function () { s += ']' }); + } + else if (typeof node == 'object') { + this.before(function () { s += '{' }); + this.pre(function (x, key) { + s += '"' + key + '"' + ':'; + }); + this.post(function (child) { + if (!child.isLast) s += ','; + }); + this.after(function () { s += '}' }); + } + else if (typeof node == 'function') { + s += 'null'; + } + else { + s += node.toString(); + } +}); + +console.log('JSON.stringify: ' + JSON.stringify(obj)); +console.log('this stringify: ' + s); diff --git a/test/stringify.js b/test/stringify.js index f9d89bd..80c97cb 100755 --- a/test/stringify.js +++ b/test/stringify.js @@ -3,8 +3,7 @@ var Traverse = require('traverse'); var sys = require('sys'); exports.stringify = function (assert) { - //var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - var obj = [ 5, 6, -3, [ 7, 8, -2, 11 ], { f : 10, g : -13 } ]; + var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; var s = ''; Traverse(obj).forEach(function (node) {