-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalanceHistoryService.js
82 lines (65 loc) · 2.15 KB
/
balanceHistoryService.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* eslint-disable no-console */
/** *
Type 🅰️
denotes a balance history where the balance amount decreases by varying amounts each month.
- decreasedByVaryingAmount
Type 🅱️
is one where the balance amount changes by the same amount each month.
- changedBySameAmount
** */
const getChangeAmount = (a, b) => (a > b ? a - b : b - a)
const decreasedByVaryingAmount = (decreasedByVaryingAmounts, previousBalance, currentBalance) => {
if (decreasedByVaryingAmounts) {
if (previousBalance < currentBalance) {
return false
}
}
return decreasedByVaryingAmounts
}
const mapResult = (decreasedByVaryingAmounts, changedBySameAmount) => {
if (decreasedByVaryingAmounts) {
return 'A'
} if (changedBySameAmount) {
return 'B'
}
return 'C'
}
const getType = (accountBalanceHistory) => {
const amountChanges = []
let i = 1
let decreasedByVaryingAmounts = true
let changedBySameAmount = true
while (i < accountBalanceHistory.length) {
const currentBalance = accountBalanceHistory[i].account.balance.amount
const previousBalance = accountBalanceHistory[i - 1].account.balance.amount
decreasedByVaryingAmounts = decreasedByVaryingAmount(
decreasedByVaryingAmounts,
previousBalance,
currentBalance,
)
const changeAmount = getChangeAmount(previousBalance, currentBalance)
if (amountChanges.length > 0) {
const previousChange = amountChanges[amountChanges.length - 1]
if (changeAmount !== previousChange) {
changedBySameAmount = false
} else {
decreasedByVaryingAmounts = false
}
if (!decreasedByVaryingAmounts && !changedBySameAmount) {
return 'C'
}
}
amountChanges.push(changeAmount)
i += 1
}
return mapResult(decreasedByVaryingAmounts, changedBySameAmount)
}
const accountTypeChecker = (accountBalanceHistory) => {
if (!accountBalanceHistory
|| !Array.isArray(accountBalanceHistory)
|| accountBalanceHistory.length < 3) return null
accountBalanceHistory
.sort((m1, m2) => (m1.monthNumber > m2.monthNumber ? 1 : -1))
return getType(accountBalanceHistory)
}
exports.accountTypeChecker = accountTypeChecker