UNPKG

react-collection-helpers

Version:
49 lines (35 loc) 1.58 kB
'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.default = sortBy; var _errorMessage = require('../helpers/error-message.helpers'); function sortBy(_ref) { var collection = _ref.collection, comparator = _ref.comparator, descending = _ref.descending, component = _ref.component; // For now, we don't accept comparators that aren't objects or functions. var type = Array.isArray(comparator) ? 'array' : typeof comparator === 'undefined' ? 'undefined' : _typeof(comparator); // Array#sort is a mutative method. Given that we're supplying it props, // we want to ensure we do not mutate it. var collectionClone = collection.slice(); switch (type) { case 'undefined': return collectionClone.sort(); case 'function': return collectionClone.sort(comparator); case 'string': return collectionClone.sort(function (a, b) { var aVal = a[comparator]; var bVal = b[comparator]; if (aVal === bVal) { return 0; } var result = aVal < bVal ? -1 : 1; return descending ? result * -1 : result; }); default: throw new Error((0, _errorMessage.invalidTypeSuppliedAsComparator)({ type: type, comparator: comparator, component: component })); } } module.exports = exports['default'];