on master help sign in
chore: cleanup/comment ensurePatFormat function
d5c7a6fMatt Condon (shrugs)
src/form/formatters.js+7−3
@@ -1,31 +1,35 @@
1import { compose, strSplice } from 'lib/lib';
1import { compose, strSplice } from 'lib/lib';
2
2
3const TICKET_MAX_BYTE_LEN = 32; // tickets can be as large as 32 bytes
3const TICKET_MAX_BYTE_LEN = 32; // tickets can be as large as 32 bytes
4+const PAT_BLOCK_CHAR_LENGTH = 6; // pat{p,q} blocks are 6 characters long
4
5
5export const buildFormatter = (formatters = []) =>
6export const buildFormatter = (formatters = []) =>
6 compose(...formatters.reverse());
7 compose(...formatters.reverse());
7
8
8/**
9/**
9− * inserts a ~ or - every 7 characters
10+ * inserts a ~ or - before every pat block
10 */
11 */
11export const ensurePatFormat = s => {
12export const ensurePatFormat = s => {
13+ // bail if falsy or empty string, nothing to do
12 if (!s || s.length === 0) {
14 if (!s || s.length === 0) {
13 return s || '';
15 return s || '';
14 }
16 }
15
17
16 // ensure there's a dash every 6 + 1 characters
18 // ensure there's a dash every 6 + 1 characters
17− const dashAt = i => i * (6 + 1);
19+ const dashAt = i => i * (PAT_BLOCK_CHAR_LENGTH + 1);
18 const maxBlocks = TICKET_MAX_BYTE_LEN / 2;
20 const maxBlocks = TICKET_MAX_BYTE_LEN / 2;
19
21
22+ // for every index that may need a separator
20 for (let i = 0; i !== maxBlocks; i++) {
23 for (let i = 0; i !== maxBlocks; i++) {
21 const dashIndex = dashAt(i);
24 const dashIndex = dashAt(i);
22
25
26+ // if the string is too short to have a separator here, we're done
23 if (s.length - 1 < dashIndex) {
27 if (s.length - 1 < dashIndex) {
24 return s;
28 return s;
25 }
29 }
26
30
31+ // insert the separator at the correct index if not already there
27 const sep = i === 0 ? '~' : '-';
32 const sep = i === 0 ? '~' : '-';
28−
29 if (s.charAt(dashIndex) !== sep) {
33 if (s.charAt(dashIndex) !== sep) {
30 s = strSplice(s, dashIndex, sep);
34 s = strSplice(s, dashIndex, sep);
31 }
35 }