UNPKG

flo-utils

Version:
89 lines (67 loc) 3.21 kB
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * 排序 树状结构 * @param {array} tree * @param {String} sort * @param {String} sortKey * @param {String} childrenKey * @return {Array} */ import isArray from './isArray'; import isObject from './isObject'; import isNumber from './isNumber'; export var DEFAULT_VALUE = []; var sortTree = function sortTree() { var te = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var sort = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'asc'; var sortKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sort'; var childrenKey = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'children'; var tree = _toConsumableArray(te); if (!isArray(tree) || !tree.length) return DEFAULT_VALUE; if (tree.length < 2) { if (tree[0][childrenKey] && tree[0][childrenKey].length) { tree[0][childrenKey] = sortTree(tree[0][childrenKey], sort, sortKey, childrenKey); } } else { tree.sort(function (m, n) { var a = m; var b = n; if (isNumber(a) && isNumber(b)) { if (sort === 'asc') { return a - b; } if (sort === 'desc') { return b - a; } return 0; } if (isObject(a) && isObject(b)) { if (a[childrenKey] && a[childrenKey].length) { a[childrenKey] = sortTree(a[childrenKey], sort, sortKey, childrenKey); } if (b[childrenKey] && b[childrenKey].length) { b[childrenKey] = sortTree(b[childrenKey], sort, sortKey, childrenKey); } if (!a[sortKey] && a[sortKey] !== 0 || !b[sortKey] && b[sortKey] !== 0) { return 0; } if (sort === 'asc') { // 升序 return a[sortKey] - b[sortKey]; } if (sort === 'desc') { return b[sortKey] - a[sortKey]; } return 0; } return 0; }); } return _toConsumableArray(tree); }; export default sortTree;