Passed
Push — master ( efcce7...8e01eb )
by Muhammad Dyas
01:31
created

state.ts ➔ getStateFromCardWhenHasHeader   C

Complexity

Conditions 10

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 4
rs 5.9999
c 0
b 0
f 0
cc 10

How to fix   Complexity   

Complexity

Complex classes like state.ts ➔ getStateFromCardWhenHasHeader often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import {PollState} from './interfaces';
2
import {chat_v1 as chatV1} from 'googleapis/build/src/apis/chat/v1';
3
4
/**
5
 * Add a new option to the state(like DB)
6
 *
7
 * @param {string} option - the new option name
8
 * @param {object} state - the current message state
9
 * @param {string} creator - who add the new option
10
 * @returns {void} card
11
 */
12
export function addOptionToState(option: string, state: PollState, creator = '') {
13
  const choiceLength = state.choices.length;
14
  state.choices.push(option);
15
  if (state.choiceCreator === undefined) {
16
    state.choiceCreator = {[choiceLength]: creator};
17
  } else {
18
    state.choiceCreator[choiceLength] = creator;
19
  }
20
}
21
22
export function getStateFromCard(event: chatV1.Schema$DeprecatedEvent) {
23
  const card = event.message?.cardsV2?.[0]?.card as chatV1.Schema$GoogleAppsCardV1Card;
24
  return getStateFromCardName(card) || getStateFromParameter(event) || getStateFromCardWhenNoHeader(card) ||
25
    getStateFromCardWhenHasHeader(card);
26
}
27
28
function getStateFromCardWhenNoHeader(card: chatV1.Schema$GoogleAppsCardV1Card) {
29
  return card?.sections?.[0].widgets?.[0].decoratedText?.button?.onClick?.action?.parameters?.[0]?.value;
30
}
31
32
function getStateFromCardWhenHasHeader(card: chatV1.Schema$GoogleAppsCardV1Card) {
33
  // when has header the first section is header
34
  return card?.sections?.[1].widgets?.[0].decoratedText?.button?.onClick?.action?.parameters?.[0]?.value;
35
}
36
37
function getStateFromCardName(card: chatV1.Schema$GoogleAppsCardV1Card) {
38
  // when has header the first section is header
39
  return card?.name;
40
}
41
42
function getStateFromParameter(event: chatV1.Schema$DeprecatedEvent) {
43
  const parameters = event.common?.parameters;
44
45
  return parameters?.['state'];
46
}
47