all files / lib/offshore/utils/ sorter.js

100% Statements 27/27
100% Branches 10/10
100% Functions 6/6
100% Lines 26/26
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                                  239× 239× 98× 98×     239× 239× 239×       186× 186× 227× 227× 227×   227× 239× 239×   227×         186× 186× 198× 111×     186× 186×    
/**
 * Module Dependencies
 */
 
var _ = require('lodash');
 
/**
 * Sort `data` (tuples) using `sortCriteria` (comparator)
 *
 * Based on method described here:
 * http://stackoverflow.com/a/4760279/909625
 *
 * @param  { Object[] } data         [tuples]
 * @param  { Object }   sortCriteria [mongo-style comparator object]
 * @return { Object[] }
 */
 
module.exports = function sortData(data, sortCriteria) {
 
  function dynamicSort(property) {
    var sortOrder = 1;
    if (property[0] === '-') {
      sortOrder = -1;
      property = property.substr(1);
    }
 
    return function(a, b) {
      var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
      return result * sortOrder;
    };
  }
 
  function dynamicSortMultiple() {
    var props = arguments;
    return function(obj1, obj2) {
      var i = 0;
      var result = 0;
      var numberOfProperties = props.length;
 
      while (result === 0 && i < numberOfProperties) {
        result = dynamicSort(props[i])(obj1, obj2);
        i++;
      }
      return result;
    };
  }
 
  // build sort criteria in the format ['firstName', '-lastName']
  var sortArray = [];
  _.each(_.keys(sortCriteria), function(key) {
    if (sortCriteria[key] === -1) sortArray.push('-' + key);
    else sortArray.push(key);
  });
 
  data.sort(dynamicSortMultiple.apply(null, sortArray));
  return data;
};