From e110a539585e8ceb6af4e9aeec356b49a3d35335 Mon Sep 17 00:00:00 2001 From: Gavin Huang Date: Wed, 26 Sep 2012 12:47:06 +0800 Subject: [PATCH 1/3] Add sorted object unit test --- tests/parse_test.js | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/parse_test.js b/tests/parse_test.js index b537d35..58989c7 100644 --- a/tests/parse_test.js +++ b/tests/parse_test.js @@ -313,6 +313,13 @@ for (var key in TESTS) (function(key) { }) })(key); +test('sorted objects', function () { + jsDump.sortKeys = true + var a = jsDump.parse({b: 2, a: 1}); + var b = '{\n "a": 1,\n "b": 2\n}' + strictEqual(a, b); +}) + if (module === require.main) { require("test").run(tests); From d5810a403520afa7a228b86d41feffdb8358dcfe Mon Sep 17 00:00:00 2001 From: Gavin Huang Date: Wed, 26 Sep 2012 12:59:44 +0800 Subject: [PATCH 2/3] Sort object keys if sortKeys is true --- jsDump.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/jsDump.js b/jsDump.js index 3f0f28a..9ff6d49 100644 --- a/jsDump.js +++ b/jsDump.js @@ -142,10 +142,18 @@ var jsDump; this._depth_ = 1; // Reset for future use throw new Error("Object nesting exceeded jsDump.maxDepth (" + jsDump.maxDepth + ")"); } - var ret = [ ]; - this.up(); + var keys = [ ]; for( var key in map ) - ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) ); + keys.push(key); + if( this.sortKeys ) + keys.sort(); + var i = keys.length, + ret = Array(i); + this.up(); + while( i-- ) { + var key = keys[i]; + ret[i] = this.parse(key,'key') + ': ' + this.parse(map[key]); + } this.down(); return join( '{', ret, '}' ); }, @@ -186,7 +194,8 @@ var jsDump; HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true, //if true, items in a collection, are separated by a \n, else just a space. - maxDepth:100 //maximum depth of object nesting + maxDepth:100, //maximum depth of object nesting + sortKeys: false, //if true, object keys will be sorted }; })(); From 07721d72b7253d01bf36c91469e50f863ced67cd Mon Sep 17 00:00:00 2001 From: Gavin Huang Date: Wed, 26 Sep 2012 13:52:04 +0800 Subject: [PATCH 3/3] window may not exist, test before using --- jsDump.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jsDump.js b/jsDump.js index 9ff6d49..67ccfd7 100644 --- a/jsDump.js +++ b/jsDump.js @@ -83,7 +83,7 @@ var jsDump; if ( 'callee' in obj ) // Opera: Object.prototype.toString.call(arguments) == 'Object' :( return 'arguments'; - else if (window.jQuery && obj instanceof window.jQuery) + else if (typeof window !== 'undefined' && window.jQuery && obj instanceof window.jQuery) return 'jquery'; else if ( 'ownerDocument' in obj && 'defaultView' in obj.ownerDocument && obj instanceof obj.ownerDocument.defaultView.Node ) return 'node';