Find and return indexes of variable declarations.


Find and return indexes of variable declarations.

This was built to run inside of twolfson/sublime-js-var-shortcuts, a Sublime Text plugin to make dealing with adding/removing vars easier.

Install the module with: npm install var-find

var varFind = require('var-find');
varFind(function abc() {
  // Group: `var def = 123;` 
  // Declaration: `def = 123;` 
  var def = 123;
} + '');
// [{ 
//   "start": 78, 
//   "end": 92, 
//   "vars": [{ 
//     "start": 82, 
//     "end": 91 
//   }] 
// }] 

varFind is a function that takes in a JS source code.

 * varFind parses JS source code and returns locations of variable groups and declarations
 * @param {String} script Source code to parse
 * @returns {Array} groups Collection of variable groups
 * @returns {Object} groups[i] Variable group instance
 * @returns {Number} groups[i].start Beginning index for variable group instance
 * @returns {Number} groups[i].end Finishing index for variable group instance
 * @returns {Array} groups[i].vars Collection of variable declarations
 * @returns {Object} groups[i].vars[i] Variable declaration instance
 * @returns {Number} groups[i].vars[i].start Beginning index for variable declaration instance
 * @returns {Number} groups[i].vars[i].end Finishing index for variable declaration instance

For visual representation, variable groups begin and end with [ and ]; for variable declarations, { and }.

Single definition:

[var {abc = 123};]

Comma-last definition:

[var {abc},

Comma-first definition:

[var {abc}
   , {def};]

Trailing whitespace (with semicolon):

Trailing whitespace without semicolon is considered another statement and ignored.

[var {abc = 123}   ;]

Support this project and others by twolfson via gittip.

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint via grunt and test via npm test.

As of Sep 27 2013, Todd Wolfson has released this repository and its contents to the public domain.

It has been released under the UNLICENSE.