Files: 7cc4808dbfe9bd370a1f0df3485981c9a7b048e4 / src / domain / block.js
1991 bytesRaw
1 | const { blockIdentifiers, blockTypes } = require('./types'); |
2 | const { ignoreGroupInBalance, readGroup } = require('./group'); |
3 | const { readRecord } = require('./record'); |
4 | const { writeNumber } = require('./number'); |
5 | |
6 | const GROUP_END_TYPE = 'group-end'; |
7 | const IGNORED = 'ignored'; |
8 | |
9 | function getBlockType(line) { |
10 | const lineFirstChar = line[0]; |
11 | |
12 | switch (lineFirstChar) { |
13 | case blockIdentifiers.GROUP: |
14 | return blockTypes.GROUP; |
15 | case blockIdentifiers.EARNING: |
16 | return blockTypes.EARNING; |
17 | case blockIdentifiers.EXPENSE: |
18 | return blockTypes.EXPENSE; |
19 | |
20 | case '': |
21 | case ' ': |
22 | case undefined: |
23 | return GROUP_END_TYPE; |
24 | |
25 | default: |
26 | return IGNORED; |
27 | } |
28 | } |
29 | |
30 | module.exports.readBlock = function readBlock(data) { |
31 | const lines = data.split('\n'); |
32 | const groupsArr = []; |
33 | let currentGroup = null; |
34 | |
35 | for (let index = 0; index < lines.length; index++) { |
36 | const line = lines[index].trim(); |
37 | const blockType = getBlockType(line); |
38 | |
39 | switch (blockType) { |
40 | case blockTypes.GROUP: // Create a group |
41 | currentGroup = readGroup(line); |
42 | continue; |
43 | case blockTypes.EARNING: |
44 | case blockTypes.EXPENSE: // Add record to current group |
45 | currentGroup.records.push(readRecord(line)); |
46 | continue; |
47 | case GROUP_END_TYPE: // Push group to groups array |
48 | if (currentGroup) groupsArr.push({ ...currentGroup }); |
49 | currentGroup = null; |
50 | continue; |
51 | } |
52 | } |
53 | |
54 | return groupsArr; |
55 | }; |
56 | |
57 | module.exports.writeBlock = function writeBlock(balance, groupsArr) { |
58 | function writeGroups(groups) { |
59 | return groups.reduce((text, group, groupIndex) => { |
60 | return `${text}${groupIndex > 0 ? ` |
61 | ` : ''}${group.toString()} |
62 | ${group.records.reduce((recordsText, record, recordIndex) => `${recordsText}${recordIndex > 0 ? ` |
63 | ` : ''}${record.toString()}`, '')} |
64 | ${blockIdentifiers.TOTAL} ${writeNumber(group.total)} |
65 | `; |
66 | }, ''); |
67 | } |
68 | |
69 | return `${blockIdentifiers.BALANCE} ${writeNumber(balance)} |
70 | |
71 | ${writeGroups(groupsArr)}`; |
72 | }; |
73 |
Built with git-ssb-web