File size: 1,616 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Read displayed monetary values without losing minus signs or binding layout.
function readAmount(text, labels) {
  const label = new RegExp(labels, 'i').exec(text);
  if (!label) throw Error(`summary label missing: ${labels}`);
  const following = text.slice(label.index + label[0].length);
  const marker = following.replace(/^\s*[::]?\s*/, '');
  const number = String.raw`\d+(?:[.,]\d+|[\u00a0\u202f ]\d{3})*`;
  // Currency codes, symbols and combined forms such as CN¥ are formatting.
  const currency = String.raw`(?:[A-Z]{2,3}\s*\p{Sc}|\p{Sc}|[A-Z]{3})`;
  const amount = new RegExp(String.raw`^([-−]?)\s*(?:${currency}\s*)?([-−]?)\s*(${number})(?:\s*${currency})?`, 'u');
  const wrapped = /^[((]([^))]+)[))]/.exec(marker);
  const match = amount.exec(wrapped ? wrapped[1].trim() : marker);
  if (!match) throw Error(`summary value missing: ${labels}`);
  const [, leadingSign, embeddedSign, digits] = match;
  const negative = Boolean(wrapped || leadingSign || embeddedSign);
  const compact = digits.replace(/\s/g, '');
  const decimalMark = /[.,]\d{1,2}$/.exec(compact);
  const value = decimalMark
    ? Number(compact.slice(0, decimalMark.index).replace(/[,.]/g, '') + '.' + decimalMark[0].slice(1))
    : Number(/^[+-]?\d{1,3}(?:[.,]\d{3})+$/.test(compact) ? compact.replace(/[.,]/g, '') : compact);
  return (negative ? -1 : 1) * value;
}

function readSummary(text) {
  return {
    expense: readAmount(text, '总支出|累计支出|总花费|Total expenses?|Expense total'),
    balance: readAmount(text, '结余|余额|Balance'),
  };
}

module.exports = {readAmount, readSummary};