# All files / src/utils walk-node.js

100% Statements 18/18
100% Branches 12/12
100% Functions 4/4
100% Lines 17/17

    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

    8064x
    225698x
    562x

    225136x

    225136x
    225136x
    5x

    225131x
    184314x

    40817x

    225136x
    97770x
    97770x

    127366x
    127365x

    127364x

    8064x

     // @flow
    import type { NodeType } from "../flow/types";

    export type WalkerType = (node: any, childMapper: any) => any | void;
    type VisitorType = { [string]: WalkerType };

    // Dead simple AST walker, takes a visitor object and calls all methods for
    // appropriate node Types.
    function walker(visitor: VisitorType): (node: NodeType) => NodeType {
      const walkNode = (node: NodeType): NodeType => {
        if (node == null) {
          return node;
        }
        const { params } = node;

        const mappingFunction: WalkerType = (() => {
          if ("*" in visitor && typeof visitor["*"] === "function") {
            return visitor["*"];
          }

          if (node.Type in visitor && typeof visitor[node.Type] === "function") {
            return visitor[node.Type];
          }

          return () => node;
        })();

        if (mappingFunction.length === 2) {
          mappingFunction(node, walkNode);
          return node;
        }

        mappingFunction(node);
        params.forEach(walkNode);

        return node;
      };

      return walkNode;
    }

    export default walker;