-
-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
working implementation with 2 examples
- Loading branch information
James Halliday
committed
Jul 16, 2013
0 parents
commit 3e5363a
Showing
3 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
var stringify = require('../'); | ||
var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; | ||
console.log(stringify(obj)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
var stringify = require('../'); | ||
var obj = { c: 6, b: [4,5], a: 3 }; | ||
console.log(stringify(obj)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
var json = typeof JSON !== 'undefined' ? JSON : require('jsonify'); | ||
|
||
module.exports = function (obj, opts) { | ||
if (!opts) opts = {}; | ||
if (typeof opts === 'function') opts = { cmp: opts }; | ||
var cmp = opts.cmp; | ||
|
||
return (function stringify (node) { | ||
if (typeof node !== 'object') { | ||
return json.stringify(node); | ||
} | ||
if (isArray(node)) { | ||
var out = []; | ||
for (var i = 0; i < node.length; i++) { | ||
out.push(stringify(node[i])); | ||
} | ||
return '[' + out.join(',') + ']'; | ||
} | ||
else { | ||
var keys = objectKeys(node).sort(cmp); | ||
var out = []; | ||
for (var i = 0; i < keys.length; i++) { | ||
var key = keys[i]; | ||
out.push(stringify(key) + ':' + stringify(node[key])); | ||
} | ||
return '{' + out.join(',') + '}'; | ||
} | ||
})(obj); | ||
}; | ||
|
||
var isArray = Array.isArray || function (x) { | ||
return {}.toString.call(x) === '[object Array]'; | ||
}; | ||
|
||
var objectKeys = Object.keys || function (obj) { | ||
var has = Object.prototype.hasOwnProperty; | ||
var keys = []; | ||
for (var key in obj) { | ||
if (has.call(obj)) keys.push(key); | ||
} | ||
return keys; | ||
}; |