# All files / src/utils trie.js

100% Statements 26/26
100% Branches 6/6
100% Functions 5/5
100% Lines 25/25

    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
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70

    26x
    21678x
    98358x
    21600x

    76758x

    21678x

    21678x

    78x

    2210x
    78x

    2210x
    2210x

    2210x

    2210x
    1482x
    1482x
    1482x

    2210x
    5720x

    5720x
    5720x
    5720x
    5720x

    2210x

    26x
     // @flow
    /**
     * A very basic trie with functional,recursive search
     */
    const fsearch = node => {
      const next = (char: string) => {
        if (node && node.children[char]) {
          return fsearch(node.children[char]);
        }

        return null;
      };

      next.leaf = node.leaf;

      return next;
    };

    type Node = {
      char: string,
      children: { [string]: Node },
      leaf: boolean,
    };

    class Trie {
      root: Node;
      fsearch: any;

      constructor(words: Array<string>) {
        this.root = {
          char: "",
          children: {},
          leaf: false,
        };

        words.map(word => this.add(word));
        this.fsearch = fsearch(this.root);
      }

      add(word: string) {
        let current = this.root;
        let char = word.slice(0, 1);

        word = word.slice(1);

        while (typeof current.children[char] !== "undefined" && char.length > 0) {
          current = current.children[char];
          char = word.slice(0, 1);
          word = word.slice(1);
        }

        while (char.length > 0) {
          const node = {
            char,
            children: {},
            leaf: false,
          };

          current.children[char] = node;
          current = node;
          char = word.slice(0, 1);
          word = word.slice(1);
        }

        current.leaf = true;
      }
    }

    module.exports = Trie;