UNPKG

2.68 kBJavaScriptView Raw
1'use strict';
2var util = require('./util');
3
4/**
5 * Parses doctest examples from a string.
6 *
7 * @param {String} input
8 * @return {Array} examples
9 */
10
11exports.run = function commentParser$run(input) {
12 return exports.parseExamples(exports.parseComments(input));
13};
14
15/**
16 * Parses comments and code from a string. Heavily inspired by the code in @tj's
17 * `dox` module
18 *
19 * @param {String} input
20 * @return {Array} parsed
21 */
22
23exports.parseComments = function commentParser$parseComments(input) {
24 input = input.replace(/\r\n/gm, '\n');
25 var nodes = [];
26
27 var insideSinglelineComment = false;
28 var insideMultilineComment = false;
29
30 var currentNode = { type: 'code', string: '', };
31
32
33 for(var i = 0, len = input.length; i < len; i += 1) {
34 if(insideMultilineComment) {
35 if(input[i] === '*' && input[i + 1] === '/') {
36 flush();
37 insideMultilineComment = false;
38 i += 1;
39 continue;
40 }
41 }
42 else if(insideSinglelineComment) {
43 if(input[i] === '\n') {
44 flush();
45 insideSinglelineComment = false;
46 continue;
47 }
48 }
49 else if(input[i] === '/') {
50 if(input[i + 1] === '*') {
51 flush();
52 currentNode.type = 'comment';
53 insideMultilineComment = true;
54 i += 1;
55 continue;
56 }
57 else if(input[i + 1] === '/') {
58 flush();
59 currentNode.type = 'comment';
60 insideSinglelineComment = true;
61 i += 1;
62 continue;
63 }
64 }
65
66 currentNode.string += input[i];
67 }
68
69 flush();
70 return nodes;
71
72 function flush() {
73 currentNode.string = util.trimString(currentNode.string);
74 nodes.push(currentNode);
75 currentNode = { type: 'code', string: '', };
76 }
77};
78
79/**
80 * Parses `jsdoc` "examples" for our doctests out of the parsed comments.
81 *
82 * @param {Array} parsedComments Parsed output from `parseComments`
83 * @return {Array} parsedExamples
84 */
85
86exports.parseExamples = function commentParser$parseExamples(parsedComments) {
87 var examples = [];
88
89 var currentExample = { expectedResult: '', };
90
91 for(var i = 0, len = parsedComments.length; i < len; i++) {
92 if(parsedComments[i].type === 'code') {
93 if(currentExample.testCase) flush();
94 currentExample.testCase = parsedComments[i].string;
95 } else if(parsedComments[i].type === 'comment' && currentExample.testCase &&
96 parsedComments[i].string.indexOf('=>') === 0) {
97 currentExample.expectedResult += parsedComments[i].string.slice(3);
98 }
99 }
100
101 flush();
102
103 return examples;
104
105 function flush() {
106 if(currentExample.expectedResult) {
107 examples.push(currentExample);
108 }
109 currentExample = { expectedResult: '', };
110 }
111};