This repository has been archived on 2022-08-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
outline/shared/utils/naturalSort.js
Gaston Flores dc92e1ead4 fix: ignore emoji when sorting (#2687)
* fix: ignore emoji when sorting

* fix: use correct flow types

* fix: use emoji-regex
2021-10-24 12:29:57 -07:00

43 lines
1002 B
JavaScript

// @flow
import emojiRegex from "emoji-regex";
import { deburr } from "lodash";
import naturalSort from "natural-sort";
type NaturalSortOptions = {
caseSensitive?: boolean,
direction?: "asc" | "desc",
};
const sorter = naturalSort();
const regex = emojiRegex();
const stripEmojis = (value: string) => value.replace(regex, "");
const cleanValue = (value: string) => stripEmojis(deburr(value));
function getSortByField<T: Object>(
item: T,
keyOrCallback: string | ((obj: T) => string)
) {
const field =
typeof keyOrCallback === "string"
? item[keyOrCallback]
: keyOrCallback(item);
return cleanValue(field);
}
function naturalSortBy<T>(
items: T[],
key: string | ((obj: T) => string),
sortOptions?: NaturalSortOptions
): T[] {
if (!items) return [];
const sort = sortOptions ? naturalSort(sortOptions) : sorter;
return items.sort((a: any, b: any): -1 | 0 | 1 =>
sort(getSortByField(a, key), getSortByField(b, key))
);
}
export default naturalSortBy;