diff --git a/README.md b/README.md index 94b9ebb..2bfc756 100644 --- a/README.md +++ b/README.md @@ -37,10 +37,11 @@ define(function (require, exports, module) { ## Usage ```javascript -javascriptStringify(value[, replacer [, space]]) +javascriptStringify(value[, replacer [, space, options]]) ``` The API is similar to `JSON.stringify`. However, any value returned by the replacer will be used literally. For this reason, the replacer is passed three arguments - `value`, `indentation` and `stringify`. If you need to continue the stringification process inside your replacer, you can call `stringify` with the updated value. +The `options` object allows to set how in-depthly a nested object will be processed. Default value is: `{ maxDepth: 100 }`. ### Examples @@ -52,6 +53,8 @@ javascriptStringify('foo'); // "'foo'" javascriptStringify({ x: 5, y: 6}); // "{x:5,y:6}" javascriptStringify([1, 2, 3, 'string']); // "[1,2,3,'string']" +javascriptStringify({ a: { b: { c: 1 } } }, undefined, undefined, { maxDepth: 2 }); // "{a:{b:{}}}" + /** * Invalid key names are automatically stringified. */ diff --git a/javascript-stringify.js b/javascript-stringify.js index ba73587..1f3bc71 100644 --- a/javascript-stringify.js +++ b/javascript-stringify.js @@ -223,14 +223,20 @@ * @param {Object} value * @param {Function} [replacer] * @param {(Number|String)} [space] + * @param {Object} [options] * @return {String} */ - return function (value, replacer, space) { + return function (value, replacer, space, options) { // Convert the spaces into a string. if (typeof space !== 'string') { space = new Array(Math.max(0, space|0) + 1).join(' '); } + + if (typeof options !== 'object') { + options = { maxDepth: 100 }; + } + var i = 0; // Prevent infinite recursion /** * Handle recursion by checking if we've visited this node every iteration. * @@ -240,12 +246,13 @@ */ var recurse = function (value, cache, next) { // If we've already visited this node before, break the recursion. - if (cache.indexOf(value) > -1) { + if (cache.indexOf(value) > -1 || i > options.maxDepth) { return; } // Push the value into the values cache to avoid an infinite loop. cache.push(value); + i++; // Stringify the value and fallback to return next(value, space, function (value) { diff --git a/test.js b/test.js index 6540929..d4cc866 100644 --- a/test.js +++ b/test.js @@ -210,4 +210,17 @@ describe('javascript-stringify', function () { expect(string).to.equal('[object Object]'); }); }); + + describe('maxDepth option', function () { + var obj = { a: { b: { c: 1 } } }; + it('should get all object', function () { + var string = stringify(obj); + expect(string).to.equal('{a:{b:{c:1}}}'); + }); + + it('should get part of the object', function () { + var string = stringify(obj, undefined, undefined, { maxDepth: 2 }); + expect(string).to.equal('{a:{b:{}}}'); + }); + }); });