UNPKG

2.32 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to check for max length on a line.
3 * @author Matt DuVall <http://www.mattduvall.com>
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = function(context) {
13
14 /**
15 * Creates a string that is made up of repeating a given string a certain
16 * number of times. This uses exponentiation of squares to achieve significant
17 * performance gains over the more traditional implementation of such
18 * functionality.
19 * @param {string} str The string to repeat.
20 * @param {int} num The number of times to repeat the string.
21 * @returns {string} The created string.
22 * @private
23 */
24 function stringRepeat(str, num) {
25 var result = "";
26 for (num |= 0; num > 0; num >>>= 1, str += str) {
27 if (num & 1) {
28 result += str;
29 }
30 }
31 return result;
32 }
33
34 var tabWidth = context.options[1];
35
36 var maxLength = context.options[0],
37 tabString = stringRepeat(" ", tabWidth);
38
39 //--------------------------------------------------------------------------
40 // Helpers
41 //--------------------------------------------------------------------------
42 function checkProgramForMaxLength(node) {
43 // Esprima does not include leading whitespace on the first line, this
44 // sets the initial range to 80 for getSource
45 node.range[0] = 0;
46 var lines = context.getSource(node) || ""; // necessary for backwards compat
47
48 // Replace the tabs
49 // Split (honors line-ending)
50 // Iterate
51 lines
52 .replace(/\t/g, tabString)
53 .split(/\r?\n/)
54 .forEach(function(line, i){
55 if (line.length > maxLength) {
56 context.report(node, { line: i + 1, col: 1 }, "Line " + (i + 1) + " exceeds the maximum line length of " + maxLength + ".");
57 }
58 });
59 }
60
61
62 //--------------------------------------------------------------------------
63 // Public API
64 //--------------------------------------------------------------------------
65
66 return {
67 "Program": checkProgramForMaxLength
68 };
69
70};