Skip to content

Instantly share code, notes, and snippets.

@RPDeshaies
Last active March 10, 2020 13:07
Show Gist options
  • Save RPDeshaies/7bc41522f7228aba0a3a9b76cb4cc7f9 to your computer and use it in GitHub Desktop.
Save RPDeshaies/7bc41522f7228aba0a3a9b76cb4cc7f9 to your computer and use it in GitHub Desktop.
type IDirection = "asc" | "desc";
export function awesomeSort<T>(
array: Array<T>,
getters: Array<(el: T) => { value: unknown; direction: IDirection }>
) {
const arrayToSort = [...array];
return arrayToSort.sort((a, b) => {
for (const getter of getters) {
const fieldType = typeof getter(a).value;
const sortingType = getter(a).direction;
if (fieldType === "number") {
const aNumber = getter(a).value as number;
const bNumber = getter(b).value as number;
const sortResult =
sortingType === "asc" ? aNumber - bNumber : bNumber - aNumber;
if (sortResult !== 0) {
return sortResult;
}
}
if (fieldType === "string") {
const aString = (getter(a).value as string).toLowerCase();
const bString = (getter(b).value as string).toLowerCase();
const sortResult =
sortingType === "asc"
? aString.localeCompare(bString)
: bString.localeCompare(aString);
if (sortResult !== 0) {
return sortResult;
}
}
}
return 0;
});
}
import { useState } from "react";
export function useSortFields<T>() {
type ISortFieldName = keyof T;
type IDirection = "asc" | "desc";
type ISortField = {
field: ISortFieldName;
direction: IDirection;
};
const [sortFields, setSortFields] = useState<Array<ISortField>>([]);
function toggleSortField(field: ISortFieldName) {
const index = sortFields.findIndex(s => s.field === field);
const element = sortFields[index];
const exists = index !== -1;
if (!exists) {
addSortField(field, "asc");
} else {
if (element.direction === "asc") {
setDirection(index, "desc");
} else {
removeSortField(index);
}
}
}
function getDirection(field: ISortFieldName): IDirection | undefined {
return sortFields.find(s => s.field === field)?.direction;
}
function getIsActive(field: ISortFieldName) {
return sortFields.find(s => s.field === field) ? true : false;
}
function addSortField(field: ISortFieldName, direction: IDirection) {
const newSortFields = [
...sortFields,
{ field: field, direction: direction } as ISortField
];
setSortFields(newSortFields);
}
function setDirection(index: number, direction: IDirection) {
const element = sortFields[index];
const newSortFields = [...sortFields];
newSortFields[index] = {
...element,
direction: direction
};
setSortFields(newSortFields);
}
function removeSortField(index: number) {
const newSortFields = sortFields.filter((sort, i) => i !== index);
setSortFields(newSortFields);
}
return { sortFields, toggleSortField, getDirection, getIsActive };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment