feat: move sort by prop to utils functions

This commit is contained in:
Oprysk 2021-12-29 12:41:39 +02:00
parent a7b75f320f
commit 62b2c864dc
3 changed files with 28 additions and 1 deletions

View File

@ -12,6 +12,7 @@ import {
SECURITY_DEFINITIONS_COMPONENT_NAME, SECURITY_DEFINITIONS_COMPONENT_NAME,
setSecuritySchemePrefix, setSecuritySchemePrefix,
JsonPointer, JsonPointer,
alphabeticallyByProp,
} from '../utils'; } from '../utils';
import { MarkdownRenderer } from './MarkdownRenderer'; import { MarkdownRenderer } from './MarkdownRenderer';
import { GroupModel, OperationModel } from './models'; import { GroupModel, OperationModel } from './models';
@ -188,9 +189,11 @@ export class MenuBuilder {
/** /**
* Returns array of Operation items for the tag * Returns array of Operation items for the tag
* @param parser
* @param parent parent OperationsGroup * @param parent parent OperationsGroup
* @param tag tag info returned from `getTagsWithOperations` * @param tag tag info returned from `getTagsWithOperations`
* @param depth items depth * @param depth items depth
* @param options - normalized options
*/ */
static getOperationsItems( static getOperationsItems(
parser: OpenAPIParser, parser: OpenAPIParser,
@ -209,9 +212,11 @@ export class MenuBuilder {
operation.depth = depth; operation.depth = depth;
res.push(operation); res.push(operation);
} }
if (options.sortOperationsAlphabetically) { if (options.sortOperationsAlphabetically) {
res.sort((a, b) => a.name.localeCompare(b.name)); res.sort(alphabeticallyByProp<OperationModel>('name'));
} }
return res; return res;
} }

View File

@ -8,3 +8,4 @@ export * from './dom';
export * from './decorators'; export * from './decorators';
export * from './debug'; export * from './debug';
export * from './memoize'; export * from './memoize';
export * from './sort';

21
src/utils/sort.ts Normal file
View File

@ -0,0 +1,21 @@
/**
* Function that returns a comparator for sorting objects by some specific key alphabetically.
*
* @param {String} property key of the object to sort, if starts from `-` - reverse
*/
export function alphabeticallyByProp<T>(property: string): (a: T, b: T) => number {
let sortOrder = 1;
if (property[0] === '-') {
sortOrder = -1;
property = property.substr(1);
}
return (a: T, b: T) => {
if (sortOrder == -1) {
return b[property].localeCompare(a[property]);
} else {
return a[property].localeCompare(b[property]);
}
};
}