Passed
Push — feature/profile-skills-finaliz... ( 961836...9d523b )
by Tristan
06:45
created

sorting.ts ➔ sortByLocalizedName   B

Complexity

Conditions 8

Size

Total Lines 53
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 36
c 0
b 0
f 0
dl 0
loc 53
rs 7.1493
cc 8

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import { localizedField, localizedFieldNonNull } from "../models/app";
2
import { Locales, localizeFieldNonNull, localizeField } from "./localize";
3
4
/**
5
 * Wrapper function to be passed to Array.sort() for objects with
6
 * a "name" property of type localizedField or localizedFieldNonNull,
7
 * sorting alphabetically.
8
 *
9
 * @param locale
10
 */
11
// eslint-disable-next-line import/prefer-default-export
12
export function sortByLocalizedName(locale: Locales) {
13
  return (
14
    first: { name: localizedField | localizedFieldNonNull },
15
    second: { name: localizedField | localizedFieldNonNull },
16
  ): number => {
17
    let firstName: string | null | undefined;
18
    let secondName: string | null | undefined;
19
20
    if (first.name.en !== null && first.name.fr !== null) {
21
      firstName = localizeFieldNonNull(
22
        locale,
23
        first as { name: localizedFieldNonNull },
24
        "name",
25
      ).toLocaleUpperCase();
26
    } else {
27
      firstName = localizeField(locale, first, "name")?.toLocaleUpperCase();
28
    }
29
30
    if (second.name.en !== null && second.name.fr !== null) {
31
      secondName = localizeFieldNonNull(
32
        locale,
33
        second as { name: localizedFieldNonNull },
34
        "name",
35
      ).toLocaleUpperCase();
36
    } else {
37
      secondName = localizeField(locale, second, "name")?.toLocaleUpperCase();
38
    }
39
40
    if (
41
      firstName !== null &&
42
      firstName !== undefined &&
43
      secondName !== null &&
44
      secondName !== undefined
45
    ) {
46
      if (firstName < secondName) {
47
        return -1;
48
      }
49
50
      if (firstName > secondName) {
51
        return 1;
52
      }
53
    }
54
55
    return 0;
56
  };
57
}
58