aboutsummaryrefslogtreecommitdiff
path: root/extension/lib/util.js
blob: d364d9593bbbc1664a80edb4f93e9d9294360e12 (plain)
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
'use strict';

/**
 * Format amount as String.
 *
 * @param amount
 *        Amount to be formatted.
 *
 * @return String, e.g. "1.23"
 */
function amount_format (amount)
{
  let separator = "." // FIXME: depends on locale
  return amount.value + separator + amount.fraction.toString().replace(/0+$/, "");
}


/**
 * Parse an amount that is specified like '5.42 EUR'.
 * Returns a {currency,value,fraction} object or null
 * if the input is invalid.
 */
function amount_parse_pretty(s) {
  let pattern = /(\d+)(.\d+)?\s*([a-zA-Z]+)/;
  let matches = pattern.exec(s);
  if (null == matches) {
    return null;
  }
  return {
    // Always succeeds due to regex
    value: parseInt(matches[1]),
    // Should we warn / fail on lost precision?
    fraction: Math.round(parseFloat(matches[2] || 0) * 1000000),
    currency: matches[3],
  };
}


/**
 * Format amount with currency as String.
 *
 * @param amount
 *        Amount to be formatted.
 *
 * @return String, e.g. "1.23 EUR"
 */
function amount_format_currency (amount)
{
  return amount_format(amount) + " " + amount.currency;
}


/**
 * Convert Date to String.
 *
 * Format: YYYY-MM-DD HH:mm
 *
 * @param date
 *        Date to be converted.
 *
 * @return String
 */
function date_format (date)
{
  function pad (number) {
    if (number < 10) {
      return '0' + number;
    }
    return number;
  }

  return date.getUTCFullYear() +
    '-' + pad(date.getUTCMonth() + 1) +
    '-' + pad(date.getUTCDate()) +
    ' ' + pad(date.getUTCHours()) +
    ':' + pad(date.getUTCMinutes());
  //':' + pad(date.getUTCSeconds());
}


/**
 * Send HTTP request.
 *
 * @param method
 *        HTTP method.
 * @param url
 *        URL to send to.
 * @param content
 *        Content of request.
 * @param content_type
 *        Content-Type HTTP header.
 * @param onsuccess
 *        Function called by XMLHttpRequest on success.
 * @param onerror
 *        Function called by XMLHttpRequest on error.
 *
 */
function http_req (method, url, content, content_type, onsuccess, onerror) {
  var req = new XMLHttpRequest();

  req.onload = function(mintEvt) {
    if (req.readyState == 4)
      onsuccess(req.status, req.responseText);
  };

  req.onerror = onerror;
  req.open(method, url, true);
  req.setRequestHeader('Content-Type', content_type);
  req.send(content);

  return req;
}