svelte-ux
Version:
- Increment version in `package.json` and commit as `Version bump to x.y.z` - `npm run publish`
49 lines (48 loc) • 1.5 kB
JavaScript
import { propAccessor } from './object';
export function createCompoundSort(...sortFns) {
return (a, b) => {
let result = 0;
for (let i = 0; i < sortFns.length; i++) {
let result = sortFns[i](a, b);
if (result != 0) {
return result;
}
}
return 0;
};
}
export function createSortFunc(valueFn, direction = 'asc') {
const sortDirection = direction === 'asc' ? 1 : -1;
return (a, b) => {
const aValue = valueFn(a);
const bValue = valueFn(b);
if (aValue == null || bValue == null) {
if (aValue == null && bValue != null) {
return -sortDirection;
}
else if (aValue != null && bValue == null) {
return sortDirection;
}
else {
// both `null`
return 0;
}
}
return aValue < bValue ? -sortDirection : aValue > bValue ? sortDirection : 0;
};
}
export function createPropertySortFunc(prop, direction = 'asc') {
return createSortFunc(propAccessor(prop), direction);
}
export function nestedSort(data, sortFunc, depth = 0) {
data.sort((a, b) => sortFunc(a, b, depth));
data.forEach((d) => {
if (d.values) {
nestedSort(d.values, sortFunc, depth + 1);
}
});
return data;
}
export function sort(arr, prop, direction = 'asc') {
return arr.sort(createPropertySortFunc(prop, direction));
}