All files / src/misc extractObjectValues.js

100% Statements 32/32
100% Branches 18/18
100% Functions 5/5
100% Lines 32/32
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        821x 821x   82x   739x   2x   1x   2x   1x       1x   3x   1x     737x         1629x   816x   813x 813x   1x   812x 812x 812x   6x   20x   6x   806x                         803x   802x   802x 808x         1x   1x 1x         10x  
"use strict";
 
function extractAllValues(callback, value, field, scale)
{
  let type = typeof value;
  if (type === 'undefined' || value === null)
  {
    return;
  }
  if (type === 'object')
  {
    if (Array.isArray(value))
    {
      for (let part of value)
      {
        extractAllValues(callback, part, field, scale);
      }
      return;
    }
    else
    {
      for (let part of Object.values(value))
      {
        extractAllValues(callback, part, field, scale);
      }
      return
    }
  }
  callback(value, field, scale);
}
 
function extractFragmentValues(callback, document, fragment, field, scale)
{
  if (fragment.length === 0)
  {
    return extractAllValues(callback, document, field, scale);
  }
  let top = fragment.splice(0, 1)[0];
  if (!document)
  {
    return;
  }
  let value = document[top];
  let type = typeof value;
  if (type === 'object' && Array.isArray(value))
  {
    for (let part of value)
    {
      extractFragmentValues(callback, part, fragment.slice(), field, scale);
    }
    return;
  }
  return extractFragmentValues(callback, value, fragment, field, scale);
}
 
 
/**
 * extract values from a document object
 *
 * @param  {object} document target document
 * @param  {object} fields   array of fields or map of fields to score
 * @param  {function} callback callback function will be called for each value
 */
function extractObjectValues(document, fields, callback)
{
  if (Array.isArray(fields))
  {
    for (let field of fields)
    {
      extractFragmentValues(callback, document, field.split('.')
        .filter(x => x !== ''), field, 1);
    }
  }
  else
  {
    for (let [field, scale] of Object.entries(fields))
    {
      extractFragmentValues(callback, document, field.split('.')
        .filter(x => x !== ''), field, scale);
    }
  }
}
 
module.exports = extractObjectValues;