Created
June 4, 2018 13:42
-
-
Save hmelenok/c34c51d2af0df4ac0d9ec7b55f77e0c0 to your computer and use it in GitHub Desktop.
javascript natural sort collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import naturalSort from 'javascript-natural-sort'; | |
import emojiStrip from 'emoji-strip'; | |
import {cloneDeep} from 'lodash'; | |
import {isOrgLib, isPersonalLib} from './directory'; | |
import {getTitle} from './properties'; | |
naturalSort.insensitive = true; | |
/** | |
* Sorts given list of Gems so that libraries come first | |
* @param {Object[]} gems Input list of Gems (any) | |
* @param {Boolean} [sortOnlyLibs=false] Flag whether only libraries should be sorted or all the input Gems | |
* @return {Object[]} Sorted Gems list | |
*/ | |
export function sortLibraries(gems, sortOnlyLibs = false) { | |
const sortedLibs = cloneDeep(gems); | |
return sortedLibs.sort((lib, nextLib) => { | |
return getLibrariesSorter(lib, nextLib, sortOnlyLibs); | |
}); | |
} | |
/** | |
* Get sorter function for libraries and groups | |
* @param {Object} a First gem for comparison | |
* @param {Object} b Second gem for comparison | |
* @param {Boolean} sortOnlyLibs Flag whether only libraries should be sorted or all the input Gems | |
* @return {Number} Result of gems comparison | |
*/ | |
export function getLibrariesSorter(a, b, sortOnlyLibs) { | |
// Bubble personal and account library to the top | |
if (isPersonalLib(a)) { | |
return -1; | |
} | |
if (isPersonalLib(b)) { | |
return 1; | |
} | |
if (isOrgLib(a)) { | |
return -1; | |
} | |
if (isOrgLib(b)) { | |
return 1; | |
} | |
if (sortOnlyLibs) { | |
return -1; | |
} | |
// Slicing title to 16 chars as natural sorting takes ~30 sec on long strings | |
const titleA = emojiStrip(getTitle(a)).slice(0, 16); | |
const titleB = emojiStrip(getTitle(b)).slice(0, 16); | |
return naturalSort(titleA, titleB); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment