Skip to content

Instantly share code, notes, and snippets.

@DungGramer
Created September 19, 2022 04:22
Show Gist options
  • Save DungGramer/c95d9fe411c7c1c61e8400c5d15b17ff to your computer and use it in GitHub Desktop.
Save DungGramer/c95d9fe411c7c1c61e8400c5d15b17ff to your computer and use it in GitHub Desktop.
Mini Sorter function
import moment from 'moment';
/**
* @param {string} dateA - a date, represented in string format
* @param {string} dateB - a date, represented in string format
*/
const date = (dateA, dateB) => moment(dateA).diff(moment(dateB));
/**
*
* @param {string} a
* @param {string} b
* @param {'asc' | 'desc'} order
*
* @return {number}
*/
const name = (a, b, order = 'asc') => {
if (!a || !b) return 0;
return order === 'asc' ? a.localeCompare(b) : b.localeCompare(a);
};
/**
* @param {Array} array
* @param {'asc' | 'desc'} order
*
* @return {Array}
* @example
* const array = [1, 2, 3, 4, 5];
* sortArray(array, 'desc') -> [5, 4, 3, 2, 1]
*/
const sortArray = (array, order = 'asc') => {
if (!Array.isArray(array)) return array;
array.sort();
return order === 'asc' ? array : array.reverse();
};
/**
* @param {Array|Object} obj
* @param {string} key
* @param {'asc' | 'desc'} order
* @return {Array|Object}
* @example
* sortObject({a: 5, b: 2, c: 3}, 'asc') -> {b: 2, c: 3, a: 5}
* sortObject([{a: 1}, {a: 9}, {a: 2}], 'a', 'desc') -> [{a: 9}, {a: 2}, {a: 1}]
*/
const sortObject = (obj, key, order = 'asc') => {
if (Array.isArray(obj) && obj.length > 0 && typeof obj[0] === 'object') {
return obj.sort((a, b) => {
if (a[key] && b[key]) {
return defaultSort(a[key], b[key], order);
}
return 0;
});
}
if (typeof obj === 'object') {
return Object.entries(obj)
.sort(([keyA, valueA], [keyB, valueB]) => {
if (valueA && valueB) {
return defaultSort(valueA, valueB, order);
}
return 0;
})
.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
}
};
/**
* @param {string} a
* @param {string} b
* @param {'asc' | 'desc'} order
*
* @return {number}
*/
const defaultSort = (a, b, order = 'asc') => {
if (!a || !b) return 0;
if (order === 'asc') {
return a > b ? 1 : -1;
}
return a > b ? -1 : 1;
};
export const Sorter = {
date,
name,
array: sortArray,
object: sortObject,
default: defaultSort,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment