-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTransaction.js
143 lines (123 loc) · 2.81 KB
/
Transaction.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import {GetMonthName, GetPreviousMonthName} from "./Datetime"
// Debit is a transaction which is subtracted.
const DEBIT = 1
// Credit is a transaction which is subtracted the next month.
const CREDIT = 2
// Income is a transaction which is summed.
const INCOME = 3
/**
* @return {object}
*/
function GroupBy(collatorFn, transactions) {
if (!transactions) return {}
return transactions.reduce((accumulator, transaction) => {
const key = collatorFn(transaction)
if (!accumulator[key]) {
accumulator[key] = [transaction]
} else {
accumulator[key].push(transaction)
}
return accumulator
}, {})
}
/**
* @return {string}
*/
function ByMonthName(transaction) {
return GetMonthName(transaction.date)
}
/**
*
* @param sorterFn function
* @param transactions array
* @returns array
*/
function SortBy(sorterFn, transactions) {
if (!transactions) return []
return transactions.sort(sorterFn)
}
/**
*
* @param a transaction
* @param b transaction
* @returns {number}
*/
function DescDateSorter(a, b) {
return new Date(b.date) - new Date(a.date)
}
/**
* @return {array}
*/
function GetTimeline(transactions) {
const currentMonth = GetMonthName(Date.now())
const timeline = Object.keys(transactions)
if (!timeline.includes(currentMonth)) {
timeline.push(currentMonth)
}
return timeline
}
/**
* @return {number}
*/
function GetBalance(month, transactions) {
let balance = 0
let creditBalance = GetCreditBalance(GetPreviousMonthName(month), transactions)
if (transactions[month] === undefined) {
return balance - creditBalance
}
transactions[month].forEach(transaction => {
switch (transaction.type) {
case INCOME:
balance += transaction.amount
break
case DEBIT:
balance -= transaction.amount
break
default:
break
}
})
return balance - creditBalance
}
/**
* @return {number}
*/
function GetCreditBalance(month, transactions) {
let balance = 0
if (transactions[month] !== undefined) {
transactions[month].forEach(transaction => {
if (transaction.type === CREDIT) {
balance += transaction.amount
}
})
}
return balance
}
/**
* @param type {CREDIT|DEBIT|INCOME}
* @returns {string}
*/
function GetTypeName(type) {
switch (type) {
case DEBIT:
return 'Debit'
case CREDIT:
return 'Credit'
case INCOME:
return 'Income'
default:
return 'Unknown'
}
}
export {
DEBIT,
CREDIT,
INCOME,
GetBalance,
GetTimeline,
GetTypeName,
GroupBy,
ByMonthName,
SortBy,
DescDateSorter
}