Skip to content

Commit

Permalink
working implementation with 2 examples
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Jul 16, 2013
0 parents commit 3e5363a
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
3 changes: 3 additions & 0 deletions example/nested.js
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));
3 changes: 3 additions & 0 deletions example/str.js
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));
42 changes: 42 additions & 0 deletions index.js
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;
};

0 comments on commit 3e5363a

Please sign in to comment.