|
| 1 | +/** |
| 2 | + * Requires capitalized constructors to to use the `new` keyword |
| 3 | + * |
| 4 | + * Types: `Boolean` or `Object` |
| 5 | + * |
| 6 | + * Values: `true` or Object with `allExcept` Array of quoted identifiers which are exempted |
| 7 | + * |
| 8 | + * JSHint: [`newcap`](http://jshint.com/docs/options/#newcap) |
| 9 | + * |
| 10 | + * #### Example |
| 11 | + * |
| 12 | + * ```js |
| 13 | + * "requireCapitalizedConstructors": true |
| 14 | + * "requireCapitalizedConstructors": { |
| 15 | + * "allExcept": ["SomethingNative"] |
| 16 | + * } |
| 17 | + * ``` |
| 18 | + * |
| 19 | + * ##### Valid |
| 20 | + * |
| 21 | + * ```js |
| 22 | + * var a = new B(); |
| 23 | + * var c = SomethingNative(); |
| 24 | + * ``` |
| 25 | + * |
| 26 | + * ##### Invalid |
| 27 | + * |
| 28 | + * ```js |
| 29 | + * var d = E(); |
| 30 | + * ``` |
| 31 | + */ |
| 32 | + |
| 33 | +var assert = require('assert'); |
| 34 | + |
| 35 | +module.exports = function() {}; |
| 36 | + |
| 37 | +module.exports.prototype = { |
| 38 | + configure: function(options) { |
| 39 | + assert( |
| 40 | + options === true || Array.isArray(options.allExcept), |
| 41 | + this.getOptionName() + ' option requires a true value or an object of exceptions' |
| 42 | + ); |
| 43 | + this._allowedConstructors = {}; |
| 44 | + |
| 45 | + var allExcept = options.allExcept; |
| 46 | + if (allExcept) { |
| 47 | + for (var i = 0, l = allExcept.length; i < l; i++) { |
| 48 | + this._allowedConstructors[allExcept[i]] = true; |
| 49 | + } |
| 50 | + } |
| 51 | + }, |
| 52 | + |
| 53 | + getOptionName: function() { |
| 54 | + return 'requireCapitalizedConstructorsNew'; |
| 55 | + }, |
| 56 | + |
| 57 | + check: function(file, errors) { |
| 58 | + var allowedConstructors = this._allowedConstructors; |
| 59 | + |
| 60 | + file.iterateNodesByType('CallExpression', function(node) { |
| 61 | + if (node.callee.type === 'Identifier' && |
| 62 | + !allowedConstructors[node.callee.name] && |
| 63 | + node.callee.name[0].toLowerCase() !== node.callee.name[0] |
| 64 | + ) { |
| 65 | + errors.add( |
| 66 | + 'Constructor functions should use the "new" keyword', |
| 67 | + node.callee.loc.start.line, |
| 68 | + node.callee.loc.start.column |
| 69 | + ); |
| 70 | + } |
| 71 | + }); |
| 72 | + } |
| 73 | + |
| 74 | +}; |
0 commit comments