Skip to content

Commit 8349489

Browse files
committed
Enable maxValues, stops stringifying after count
1 parent e3b1a2b commit 8349489

File tree

2 files changed

+10
-7
lines changed

2 files changed

+10
-7
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,9 @@ The API is similar to `JSON.stringify`. However, any value returned by the repla
4444

4545
The `options` object allows some additional configuration:
4646

47-
* **maxDepth** _(number)_ The maximum depth of values to stringify
48-
* **references** _(boolean)_ Restore circular/repeated references in the object (uses IIFE)
47+
* **maxDepth** _(number, default: 100)_ The maximum depth of values to stringify
48+
* **maxValues** _(number, default: 100000)_ The maximum number of values to stringify
49+
* **references** _(boolean, default: false)_ Restore circular/repeated references in the object (uses IIFE)
4950

5051
### Examples
5152

@@ -79,6 +80,7 @@ var obj = { x: 10 };
7980
obj.circular = obj;
8081

8182
javascriptStringify(obj); // "{x:10}"
83+
javascriptStringify(obj, null, null, { references: true }); // "(function(){var x={x:10};x.circular=x;return x;}())"
8284

8385
/**
8486
* Specify indentation - just like `JSON.stringify`.

javascript-stringify.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@
253253

254254
var maxDepth = Number(options.maxDepth) || 100;
255255
var references = !!options.references;
256+
var valueCount = Number(options.maxValues) || 100000;
256257

257258
var path = [];
258259
var stack = [];
@@ -284,11 +285,11 @@
284285
var recurse = references ?
285286
function (value, stringify) {
286287
if (value && (typeof value === 'object' || typeof value === 'function')) {
287-
var exists = encountered.indexOf(value);
288+
var seen = encountered.indexOf(value);
288289

289290
// Track nodes to restore later.
290-
if (exists > -1) {
291-
restore.push(path.slice(), paths[exists]);
291+
if (seen > -1) {
292+
restore.push(path.slice(), paths[seen]);
292293
return;
293294
}
294295

@@ -298,7 +299,7 @@
298299
}
299300

300301
// Stop when we hit the max depth.
301-
if (path.length > maxDepth) {
302+
if (path.length > maxDepth || valueCount-- <= 0) {
302303
return;
303304
}
304305

@@ -308,7 +309,7 @@
308309
function (value, stringify) {
309310
var seen = stack.indexOf(value);
310311

311-
if (seen > -1 || path.length > maxDepth) {
312+
if (seen > -1 || path.length > maxDepth || valueCount-- <= 0) {
312313
return;
313314
}
314315

0 commit comments

Comments
 (0)