-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
41 lines (32 loc) · 1.09 KB
/
index.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
'use strict';
/**
* Function to decode the address format
*
* @param {String} address - given encoded address
* @param {Array<String>} fields - the case sensitive fields that the encoded address need to have
*/
function decode(address, fields) {
if (!address) throw new Error('Missing "address" input');
let requiredFields = fields || [];
const result = address.split('|').reduce((accumulator, item) => {
const key = item.split(':')[0];
const value = item.split(':')[1];
if (!key) throw new Error(`Invalid key ${key}`);
if (!value) throw new Error(`Invalid value ${value}`);
if (Object.prototype.hasOwnProperty.call(accumulator, key)) {
throw new Error(`Detect duplication of field ${key} in fromAddress or toAddress`);
}
if (requiredFields.indexOf(key) !== -1) {
requiredFields = requiredFields.filter((field) => field !== key);
}
accumulator[key] = value;
return accumulator;
}, {});
if (requiredFields.length !== 0) {
throw new Error(`Missing ${requiredFields} from input text`);
}
return result;
}
module.exports = {
decode,
};