on a751ef0 help sign in
bridge/src/form/formatters.js
79 lines 1.7 kB history raw
1import { compose, strSplice } from 'lib/lib';
2import convertToInt from 'lib/convertToInt';
4const HEX_PREFIX = '0x';
5const TICKET_MAX_BYTE_LEN = 32; // tickets can be as large as 32 bytes
6const PAT_BLOCK_CHAR_LENGTH = 6; // pat{p,q} blocks are 6 characters long
8export const buildFormatter = (formatters = []) =>
9 compose(...formatters.reverse());
11/**
12 * inserts a ~ or - before every pat block
13 */
14export const ensurePatFormat = s => {
15 // bail if falsy or empty string, nothing to do
16 if (!s || s.length === 0) {
17 return s || '';
18 }
20 // ensure there's a dash every 6 + 1 characters
21 const dashAt = i => i * (PAT_BLOCK_CHAR_LENGTH + 1);
22 const maxBlocks = TICKET_MAX_BYTE_LEN / 2;
24 // for every index that may need a separator
25 for (let i = 0; i !== maxBlocks; i++) {
26 const dashIndex = dashAt(i);
28 // if the string is too short to have a separator here, we're done
29 if (s.length - 1 < dashIndex) {
30 return s;
31 }
33 // insert the separator at the correct index if not already there
34 const sep = i === 0 ? '~' : '-';
35 if (s.charAt(dashIndex) !== sep) {
36 s = strSplice(s, dashIndex, sep);
37 }
38 }
40 return s;
41};
43export const ensureHexPrefix = s => {
44 if (!s || s.length < HEX_PREFIX.length) {
45 return s || '';
46 }
48 return s.indexOf(HEX_PREFIX) !== 0 ? `${HEX_PREFIX}${s}` : s;
49};
51export const convertToNumber = s => {
52 if (!s) {
53 return s || '';
54 }
56 try {
57 return convertToInt(s, 10);
58 } catch {
59 return 0;
60 }
61};
63export const downcase = s => {
64 if (!s) {
65 return s;
66 }
68 return s.toLowerCase();
69};
71export const stripHexPrefix = s => {
72 if (!s) {
73 return s;
74 }
76 return s.toLowerCase().indexOf(HEX_PREFIX) === 0
77 ? s.slice(HEX_PREFIX.length)
78 : s;
79};