'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.filter = filter;
exports.facet = facet;
exports.find = find;
exports.removeByAttr = removeByAttr;
exports.contains = contains;
/**
 * Highly efficient filter on a value in an object
 * @param  {Array} arr   the array of objects
 * @param  {string} attr the attribute to filter on
 * @param  {mixed} value the value to compare
 * @return {Array}       the filtered array
 */
function filter(arr, attr, value) {
  var len = arr.length;
  var result = [];
  var i = 0;

  for (; i < len; i += 1) {
    var elt = arr[i];

    if (elt[attr] == value) {
      result.push(elt);
    }
  }
  return result;
}

/**
 * Highly efficient facet on a value in an object
 * Works also for nested properties
 * @param  {Array} arr   the array of objects to search
 * @param  {Array} attrs the attributes to facet on
 * @param  {mixed} value the value to compare
 * @return {Array}       the filtered array
 */
function facet(arr, attrs, value) {
  var searches = [];
  Array.prototype.forEach.call(attrs, function (attr) {
    var attrPath = attr.split('.');
    searches.push(attrPath);
  });

  var len = arr.length;
  var result = [];
  var i = 0;

  for (; i < len; i += 1) {
    var elt = arr[i];
    var found = false;
    Array.prototype.forEach.call(searches, function (search) {
      var j = 0;
      var a = arr[i];
      while (j < search.length) {
        a = a[search[j]];j++;
      }
      if (a.indexOf(value) !== -1) {
        found = true;
      }
    });

    if (found) {
      result.push(elt);
    }
  }

  return result;
}

/**
 * Highly efficient find indexes on a value in a property of an object
 * Works also for nested properties
 * @param  {Array} arr   the array of objects
 * @param  {string} attr the attribute to filter on
 * @param  {mixed} value the value to compare
 * @return {Array}       the filtered array of indexes
 */
function find(arr, attr, value) {
  var len = arr.length;
  var result = [];
  var i = 0;

  for (; i < len; i += 1) {
    var elt = arr[i];

    if (elt[attr] == value) {
      result.push(i);
    }
  }
  return result;
}

/**
 * Remove objects from an array given an attribute value
 * @param  {Array} arr   the array of objects
 * @param  {string} attr the attribute to filter on
 * @param  {mixed} value the value to compare
 * @return {Array}       the array with corresponding objects removed
 */
function removeByAttr(arr, attr, value) {
  var i = arr.length;
  while (i--) {
    if (arr[i] && arr[i].hasOwnProperty(attr) && arguments.length > 2 && arr[i][attr] === value) {
      arr.splice(i, 1);
    }
  }

  return arr;
}

function contains(arr, obj) {
  var i = arr.length;
  while (i--) {
    if (arr[i] === obj) {
      return true;
    }
  }
  return false;
}