'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var byColumns = function byColumns(sortingColumns, selectedColumn) {
  var index = sortingColumns && sortingColumns.map(function (c) {
    return c.property;
  }).indexOf(selectedColumn);
  var newSortingColumns = [];

  if (!sortingColumns) {
    return [{
      property: selectedColumn,
      sort: 'asc'
    }];
  } else if (index >= 0) {
    newSortingColumns = sortingColumns;

    var newSort = cycleSort(newSortingColumns[index].sort);

    if (newSort) {
      newSortingColumns[index] = {
        property: selectedColumn,
        sort: newSort
      };
    } else {
      newSortingColumns.splice(index, 1);
    }

    return newSortingColumns;
  }

  return [].concat(_toConsumableArray(sortingColumns), [{
    property: selectedColumn,
    sort: 'asc'
  }]);
};

function cycleSort(sort) {
  if (!sort) {
    return 'asc';
  } else if (sort === 'asc') {
    return 'desc';
  }

  return null;
}

// sorter === lodash orderBy
// https://lodash.com/docs#orderBy
byColumns.sort = function (data, columns, sorter) {
  if (!columns) {
    return data;
  }

  var propertyList = [];
  var orderList = [];

  columns.forEach(function (column) {
    propertyList.push(column.property);
    orderList.push(column.sort);
  });

  return sorter(data, propertyList, orderList);
};

exports.default = byColumns;