From 62b2c864dcc766d0154829de505581dec1c88f8b Mon Sep 17 00:00:00 2001 From: Oprysk Date: Wed, 29 Dec 2021 12:41:39 +0200 Subject: [PATCH] feat: move sort by prop to utils functions --- src/services/MenuBuilder.ts | 7 ++++++- src/utils/index.ts | 1 + src/utils/sort.ts | 21 +++++++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 src/utils/sort.ts diff --git a/src/services/MenuBuilder.ts b/src/services/MenuBuilder.ts index ded2eed4..a31a5322 100644 --- a/src/services/MenuBuilder.ts +++ b/src/services/MenuBuilder.ts @@ -12,6 +12,7 @@ import { SECURITY_DEFINITIONS_COMPONENT_NAME, setSecuritySchemePrefix, JsonPointer, + alphabeticallyByProp, } from '../utils'; import { MarkdownRenderer } from './MarkdownRenderer'; import { GroupModel, OperationModel } from './models'; @@ -188,9 +189,11 @@ export class MenuBuilder { /** * Returns array of Operation items for the tag + * @param parser * @param parent parent OperationsGroup * @param tag tag info returned from `getTagsWithOperations` * @param depth items depth + * @param options - normalized options */ static getOperationsItems( parser: OpenAPIParser, @@ -209,9 +212,11 @@ export class MenuBuilder { operation.depth = depth; res.push(operation); } + if (options.sortOperationsAlphabetically) { - res.sort((a, b) => a.name.localeCompare(b.name)); + res.sort(alphabeticallyByProp('name')); } + return res; } diff --git a/src/utils/index.ts b/src/utils/index.ts index dd19252f..c25ed970 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -8,3 +8,4 @@ export * from './dom'; export * from './decorators'; export * from './debug'; export * from './memoize'; +export * from './sort'; diff --git a/src/utils/sort.ts b/src/utils/sort.ts new file mode 100644 index 00000000..4c3536ad --- /dev/null +++ b/src/utils/sort.ts @@ -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(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]); + } + }; +}