ec68611b72eb90f16f1315a076fe59a880adafca
[platform/framework/web/crosswalk-tizen.git] /
1 /**
2  * @fileoverview Rule to flag creation of function inside a loop
3  * @author Ilya Volodin
4  * @copyright 2013 Ilya Volodin. All rights reserved.
5  */
6
7 "use strict";
8
9 //------------------------------------------------------------------------------
10 // Rule Definition
11 //------------------------------------------------------------------------------
12
13 module.exports = function(context) {
14     var loopNodeTypes = [
15         "ForStatement",
16         "WhileStatement",
17         "ForInStatement",
18         "ForOfStatement",
19         "DoWhileStatement"
20     ];
21
22     /**
23      * Checks if the given node is a loop.
24      * @param {ASTNode} node The AST node to check.
25      * @returns {boolean} Whether or not the node is a loop.
26      */
27     function isLoop(node) {
28         return loopNodeTypes.indexOf(node.type) > -1;
29     }
30
31     /**
32      * Reports if the given node has an ancestor node which is a loop.
33      * @param {ASTNode} node The AST node to check.
34      * @returns {boolean} Whether or not the node is within a loop.
35      */
36     function checkForLoops(node) {
37         var ancestors = context.getAncestors();
38
39         if (ancestors.some(isLoop)) {
40             context.report(node, "Don't make functions within a loop");
41         }
42     }
43
44     return {
45         "ArrowFunctionExpression": checkForLoops,
46         "FunctionExpression": checkForLoops,
47         "FunctionDeclaration": checkForLoops
48     };
49 };