diff --git a/src/bundles/files.js b/src/bundles/files.js index d4d9d92bd..f44316504 100644 --- a/src/bundles/files.js +++ b/src/bundles/files.js @@ -2,6 +2,7 @@ import { join, dirname } from 'path' import { createSelector } from 'redux-bundler' import { getDownloadLink, getShareableLink, filesToStreams } from '../lib/files' import countDirs from '../lib/count-dirs' +import { sortByName, sortBySize } from '../lib/sort' const isMac = navigator.userAgent.indexOf('Mac') !== -1 @@ -21,18 +22,6 @@ export const sorts = { BY_SIZE: 'size' } -function compare (a, b, asc) { - const strings = typeof a === 'string' && typeof b === 'string' - - if (strings ? a.toLowerCase() > b.toLowerCase() : a > b) { - return asc ? 1 : -1 - } else if (strings ? a.toLowerCase() < b.toLowerCase() : a < b) { - return asc ? -1 : 1 - } else { - return 0 - } -} - const make = (basename, action) => (...args) => async (args2) => { const id = Symbol(basename) const { dispatch, getIpfs, store } = args2 @@ -351,6 +340,9 @@ export default (opts = {}) => { selectFiles: (state) => { const { pageContent, sorting } = state.files + const sortDir = sorting.asc ? 1 : -1 + const nameSort = sortByName(sortDir) + const sizeSort = sortBySize(sortDir) if (pageContent === null || pageContent.type === 'file') { return pageContent @@ -361,9 +353,9 @@ export default (opts = {}) => { content: pageContent.content.sort((a, b) => { if (a.type === b.type || isMac) { if (sorting.by === sorts.BY_NAME) { - return compare(a.name, b.name, sorting.asc) + return nameSort(a.name, b.name) } else { - return compare(a.cumulativeSize || a.size, b.cumulativeSize || b.size, sorting.asc) + return sizeSort(a.cumulativeSize || a.size, b.cumulativeSize || b.size) } } diff --git a/src/lib/sort.js b/src/lib/sort.js new file mode 100644 index 000000000..5c1f185c6 --- /dev/null +++ b/src/lib/sort.js @@ -0,0 +1,18 @@ +/** + * Natural sort comparator for strings. + * + * @param {Number} dir - sorting direction, 1 for ascending or -1 for descending + * @param {Object} opts - localeCompare options (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) + */ +export function sortByName (dir = 1, opts = { numeric: true, sensitivity: 'base' }) { + return (a, b) => a.localeCompare(b, undefined, opts) * dir +} + +/** + * Numerical sort comparator. + * + * @param {Number} dir - sorting direction, 1 for ascending or -1 for descending + */ +export function sortBySize (dir = 1) { + return (a, b) => (a - b) * dir +}