-
Notifications
You must be signed in to change notification settings - Fork 0
/
generateExternalId.ts
57 lines (54 loc) · 1.42 KB
/
generateExternalId.ts
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
import { FormTypes } from '@oneblink/types'
import { customAlphabet } from 'nanoid/non-secure'
import { format } from 'date-fns'
export const dateFormatMap: Record<FormTypes.ReceiptDateFormat, string> = {
dayOfMonth: 'dd',
monthNumber: 'MM',
yearShort: 'yy',
year: 'yyyy',
}
export function buildAlphabet(
alphabetConfig: FormTypes.ReceiptRandomComponent,
) {
let alphabet = ''
// all letters except i o and l
const allowedLetters = 'abcdefghjkmnpqrstuvwxyz'
if (alphabetConfig.lowercase) {
alphabet += allowedLetters
}
if (alphabetConfig.uppercase) {
alphabet += allowedLetters.toUpperCase()
}
if (alphabetConfig.numbers) {
// all numbers except 0
alphabet += '123456789'
}
return alphabet
}
export function generateExternalId(
receiptComponents: FormTypes.ReceiptComponent[],
) {
const date = new Date()
return receiptComponents.reduce((id: string, component) => {
switch (component.type) {
case 'text':
return id + component.value
case 'date': {
const dateFormat = dateFormatMap[component.format]
if (dateFormat) {
return id + format(date, dateFormat)
}
break
}
case 'random': {
const alphabet = buildAlphabet(component)
if (alphabet) {
const randomFunc = customAlphabet(alphabet, component.length)
return id + randomFunc()
}
break
}
}
return id
}, '')
}