From e093716ebedd9b092120f488ec8bf0d97f0c53d4 Mon Sep 17 00:00:00 2001 From: Jeff Williams Date: Fri, 5 Sep 2014 15:12:57 -0700 Subject: [PATCH] handle sparse arrays correctly in nodeToString (#749) --- lib/jsdoc/src/astnode.js | 7 ++++++- test/specs/jsdoc/src/astnode.js | 7 ++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/jsdoc/src/astnode.js b/lib/jsdoc/src/astnode.js index f82254bb..26782164 100644 --- a/lib/jsdoc/src/astnode.js +++ b/lib/jsdoc/src/astnode.js @@ -138,8 +138,13 @@ var nodeToString = exports.nodeToString = function(node) { case Syntax.ArrayExpression: tempObject = []; node.elements.forEach(function(el, i) { + // handle sparse arrays. use `null` to represent missing values, consistent with + // JSON.stringify([,]). + if (!el) { + tempObject[i] = null; + } // preserve literal values so that the JSON form shows the correct type - if (el.type === Syntax.Literal) { + else if (el.type === Syntax.Literal) { tempObject[i] = el.value; } else { diff --git a/test/specs/jsdoc/src/astnode.js b/test/specs/jsdoc/src/astnode.js index 24ba2c82..6e1f35db 100644 --- a/test/specs/jsdoc/src/astnode.js +++ b/test/specs/jsdoc/src/astnode.js @@ -13,6 +13,7 @@ describe('jsdoc/src/astnode', function() { }; // create the AST nodes we'll be testing + var arrayExpression = esprima.parse('[,]').body[0].expression; var assignmentExpression = esprima.parse('foo = 1;').body[0].expression; var binaryExpression = esprima.parse('foo & foo;').body[0].expression; var functionDeclaration1 = esprima.parse('function foo() {}').body[0]; @@ -793,6 +794,10 @@ describe('jsdoc/src/astnode', function() { }); describe('nodeToString', function() { + it('should return `[null]` for the sparse array `[,]`', function() { + expect( astnode.nodeToString(arrayExpression) ).toBe('[null]'); + }); + it('should return the variable name for assignment expressions', function() { expect( astnode.nodeToString(assignmentExpression) ).toBe('foo'); }); @@ -848,7 +853,7 @@ describe('jsdoc/src/astnode', function() { }); it('should return the variable name for variable declarators', function() { - expect ( astnode.nodeToString(variableDeclarator1) ).toBe('foo'); + expect( astnode.nodeToString(variableDeclarator1) ).toBe('foo'); }); it('should return an empty string for all other nodes', function() {