Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3e5363a

Browse files
author
James Halliday
committed
working implementation with 2 examples
0 parents commit 3e5363a

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

‎example/nested.js‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
var stringify = require('../');
2+
var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
3+
console.log(stringify(obj));

‎example/str.js‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
var stringify = require('../');
2+
var obj = { c: 6, b: [4,5], a: 3 };
3+
console.log(stringify(obj));

‎index.js‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
var json = typeof JSON !== 'undefined' ? JSON : require('jsonify');
2+
3+
module.exports = function (obj, opts) {
4+
if (!opts) opts = {};
5+
if (typeof opts === 'function') opts = { cmp: opts };
6+
var cmp = opts.cmp;
7+
8+
return (function stringify (node) {
9+
if (typeof node !== 'object') {
10+
return json.stringify(node);
11+
}
12+
if (isArray(node)) {
13+
var out = [];
14+
for (var i = 0; i < node.length; i++) {
15+
out.push(stringify(node[i]));
16+
}
17+
return '[' + out.join(',') + ']';
18+
}
19+
else {
20+
var keys = objectKeys(node).sort(cmp);
21+
var out = [];
22+
for (var i = 0; i < keys.length; i++) {
23+
var key = keys[i];
24+
out.push(stringify(key) + ':' + stringify(node[key]));
25+
}
26+
return '{' + out.join(',') + '}';
27+
}
28+
})(obj);
29+
};
30+
31+
var isArray = Array.isArray || function (x) {
32+
return {}.toString.call(x) === '[object Array]';
33+
};
34+
35+
var objectKeys = Object.keys || function (obj) {
36+
var has = Object.prototype.hasOwnProperty;
37+
var keys = [];
38+
for (var key in obj) {
39+
if (has.call(obj)) keys.push(key);
40+
}
41+
return keys;
42+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /