# 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

    28x
    17386x
    73197x
    17302x

    55895x

    17386x

    17386x

    84x

    2016x
    84x

    2016x
    2016x

    2016x

    2016x
    1120x
    1120x
    1120x

    2016x
    4928x

    4928x
    4928x
    4928x
    4928x

    2016x

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