All files / src/processors Sorter.js

86.67% Statements 26/30
86.67% Branches 13/15
100% Functions 6/6
86.67% Lines 26/30
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    9x   9x           18x         10x   10x   10x   2x   2x 2x   8x                 10x 10x   24x                     10x 10x 10x   24x 24x 24x         8x           8x     16x   10x       6x           9x   9x    
"use strict";
 
const Processor = require('./Processor');
 
const PROCESSOR_TYPE = 'sorter';
 
class Sorter extends Processor
{
  constructor(config = {})
  {
    super(config, PROCESSOR_TYPE, ['results']);
  }
 
  async processResults(system, query, results)
  {
    try
    {
      let sort = query.sort ? query.sort : 'score';
      // load sort value if not score
      if (sort !== 'score')
      {
        try
        {
          const index = system.indicesLookup[sort][0];
          results.results.forEach(result =>
          {
            result[sort] = index.getSortValue(result._index);
          });
        }
        catch (e)
        {
          console.log(e.stack)
          sort = 'score';
        }
      }
      results.results.sort(this.sortFunction(system, sort, query.order));
      results.results.forEach(result =>
      {
        result._index = undefined;
      })
    }
    catch (e)
    {
      console.error(e.stack)
    }
  }
 
  sortFunction(system, sort, sortOrder)
  {
    const idField = system.idField;
    const order = sort === 'score' ? 1 : (sortOrder === 'asc' ? -1 : 1);
    return (a, b) =>
    {
      const asort = a[sort],
        bsort = b[sort];
      if (asort === bsort)
      {
        // document ids are assumed to never be equal
        // when sorts are equal, order by document ids
        // they could mean something. e.g. file path or omething
        Iif (a[idField] > b[idField])
        {
          return 1;
        }
        else
        {
          return -1;
        }
      }
      else if (bsort > asort)
      {
        return order;
      }
      else
      {
        return -order;
      }
    };
  }
}
 
module.exports = Sorter;
// register type for serialisation
require('./register')
  .add(Sorter, PROCESSOR_TYPE);