Code coverage report for multilang-extract-comments/index.js

Statements: 100% (28 / 28)      Branches: 100% (11 / 11)      Functions: 100% (5 / 5)      Lines: 100% (28 / 28)      Ignored: none     

All files » multilang-extract-comments/ » index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                  1 1 1   1 167     1 6 5 5     6 6   6             6 6 6 6     248       254     254 254     248 248 248 6   242   248         6     1  
/*!
 * multilang-extract-comments <https://github.com/nknapp/multilang-extract-comments>
 *
 * Copyright (c) 2015 Nils Knappmeier.
 * Released under the MIT license.
 */
 
'use strict'
 
var cp = require('comment-patterns')
var Scanner = require('./scanner.js')
var nextLineRegex = /.*$/mg
 
function identityFunction (x) {
  return x
}
 
function extract (str, fn, options) {
  if (typeof fn !== 'function' && typeof options === 'undefined') {
    options = fn
    fn = identityFunction
  }
  // default filename is a javascript file (for backwards compatibility)
  var filename = (options && options.filename) || 'abc.js'
  var regexp = cp.regex(filename)
 
  var result = {}
 
  // This variable is an intermediate
  // store for comments that have been extracted,
  // but the next-line-of-code is still missing
  // This property is not set until the following
  // comment is processed.
  var lastComment = null
  var codeStart = null
  var codeEnd = null
  new Scanner(regexp)
    .on('comment', function (comment) {
      // Temporary save the comment
      lastComment = comment
    })
    .on('codeStart', function (codeStartIndex) {
      // Save the index of the first line of code after the comment
      codeStart = codeStartIndex
    })
    .on('codeEnd', function (codeEndIndex) {
      codeEnd = codeEndIndex
      if (lastComment) {
        // Finalize the last comment: Retrieve the first line of code.
        // At most up to the next comment
        nextLineRegex.lastIndex = codeStart
        var match = nextLineRegex.exec(str)
        if (match[0].length > codeEnd - codeStart) {
          lastComment.code = match[0].substr(codeEnd - codeStart)
        } else {
          lastComment.code = match[0]
        }
        result[lastComment.begin] = fn(lastComment, lastComment.begin, lastComment.end)
      }
    })
    .scan(str)
 
  return result
}
 
module.exports = extract