All files / src Results.js

100% Statements 35/35
93.75% Branches 15/16
100% Functions 7/7
100% Lines 35/35
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114                  217x 217x         166x         82x               116x   180x   116x   5x       116x 116x         8x   4x   2x     8x   6x   2x     8x   8x       8x 8x         3x   36x   24x   4x       20x         12x     3x         93x 93x 93x 93x   174x           93x 93x             10x  
"use strict";
 
/**
 * Search Results
 */
class Results
{
  constructor()
  {
    this.keywords = [];
    this.results = {};
  }
 
  addHit(index, hit)
  {
    this.results[index] = (this.results[index] || 0) + hit;
  }
 
  addKeyword(keyword, hits)
  {
    this.keywords.push({
      keyword,
      hits
    });
  }
 
  concat(results)
  {
    for (const [index, score] of Object.entries(results.results))
    {
      this.results[index] = (this.results[index] || 0) + score;
    }
    if (this.keywords.length)
    {
      this.keywords.push({
        keyword: 'or'
      });
    }
    this.keywords = this.keywords.concat(results.keywords)
    return this;
  }
 
  merge(results)
  {
    for (const index of Object.keys(this.results))
    {
      if (!results.results[index])
      {
        delete this.results[index];
      }
    }
    for (const [index, score] of Object.entries(results.results))
    {
      if (this.results[index])
      {
        this.results[index] = this.results[index] * score;
      }
    }
    Eif (this.keywords.length)
    {
      this.keywords.push({
        keyword: 'and'
      });
    }
    this.keywords = this.keywords.concat(results.keywords)
    return this;
  }
 
  invert(indices)
  {
    for (let index = 0; index < indices.length; index++)
    {
      if (indices[index] !== null)
      {
        if (this.results[index])
        {
          delete this.results[index]
        }
        else
        {
          this.results[index] = 1;
        }
      }
      else
      {
        delete this.results[index]
      }
    }
    return this;
  }
 
  normalise(config)
  {
    const idField = config.idField;
    const ids = config.ids;
    const results = [];
    for (const [index, score] of Object.entries(this.results))
    {
      results.push({
        _index: index,
        [idField]: ids[index],
        score: score
      });
    }
    const keywords = this.keywords;
    return {
      keywords,
      results
    };
  }
}
 
module.exports = Results;