# all files / src/ formatters.jsx

100% Statements 22/22
100% Branches 6/6
100% Functions 3/3
100% Lines 16/16
1 branch Ignored

    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
    437×

    7×

    4×
    4×
    4×
    4×

    4×
    3×

    3×

    3×

    3×
    1×

    3×

    4×

    4×

     import React from 'react';

    const highlight = getHighlights => value => {
      const val = String(value); // deals with arrays/numbers/...

      const highlights = getHighlights(val);
      let children = [];
      let currentPosition = 0;
      let x = 0;

      for (x = 0; x < highlights.length; x++) {
        const nonMatchingPrefix = val.slice(
          currentPosition,
          highlights[x].startIndex
        );
        const matchingText = val.slice(
          highlights[x].startIndex,
          highlights[x].startIndex + highlights[x].length
        );

        currentPosition = highlights[x].startIndex + highlights[x].length;

        if (nonMatchingPrefix.length > 0) {
          children.push(
            <span key={`${x}-nonmatch`}>{nonMatchingPrefix}</span>
          );
        }
        children.push(
          <span className="highlight" key={`${x}-match`}>{matchingText}</span>
        );
      }
      children.push(
        <span key={`${x}-remainder`}>{val.slice(currentPosition)}</span>
      );

      return <span className="search-result">{children}</span>;
    };

    export default {
      highlight
    };