Skip to content

Instantly share code, notes, and snippets.

@RadoslawB
Created March 19, 2020 20:17
Show Gist options
  • Save RadoslawB/f270020c694f40ef99e955258ba01398 to your computer and use it in GitHub Desktop.
Save RadoslawB/f270020c694f40ef99e955258ba01398 to your computer and use it in GitHub Desktop.
Javascript/Typescript sort decorator
/**
* * Decorator for methods returning T[]; where T has property fieldName
* @param fieldName: string, property name to sort by; reference _.orderBy documentation
* @param direction: string; reference _.orderBy documentation
*/
export function Sort<T>(fieldName: keyof T, direction: SortDirection = 'asc'): any {
return function(target: any, propertyKey: string, descriptor: PropertyDescriptor): PropertyDescriptor {
const original = descriptor.value;
descriptor.value = function(...args: any[]): any {
const result = original.apply(this, args);
return _.orderBy(result, [v => v[fieldName].toLowerCase()], direction);
};
return descriptor;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment