# 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

    9895x
    213599x
    620x

    212979x

    212979x
    212979x
    5x

    212974x
    169417x

    43557x

    212979x
    88451x
    88451x

    124528x
    124527x

    124526x

    9895x

     // @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;