forked from date-fns/date-fns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.js
90 lines (72 loc) · 1.97 KB
/
common.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
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
const { addSeparator, formatBlock } = require('./formatBlock')
const lowerCaseTypes = ['String', 'Number', 'Boolean']
function correctTypeCase(type) {
if (lowerCaseTypes.includes(type)) {
return type.toLowerCase()
}
return type
}
function getParams(params, { leftBorder = '{', rightBorder = '}' } = {}) {
if (!params || params.length === 0) {
return leftBorder + rightBorder
}
const formattedParams = addSeparator(
params.map(param => {
const {
name,
props,
optional,
variable,
type: { names: typeNames }
} = param
const type = getType(typeNames, { props, forceArray: variable })
return `${variable ? '...' : ''}${name}${optional ? '?' : ''}: ${type}`
}),
','
)
return formatBlock`
${leftBorder}
${formattedParams}
${rightBorder}
`
}
function getType(types, { props = [], forceArray = false } = {}) {
const typeStrings = types.map(type => {
if (type === '*') {
return 'any'
}
if (type === 'function') {
return 'Function'
}
if (type.startsWith('Array.')) {
const [, arrayType] = type.match(/^Array\.<(\w+)>$/i)
return `${correctTypeCase(arrayType)}[]`
}
if (type === 'Object' && props.length > 0) {
return getParams(props)
}
const caseCorrectedType = correctTypeCase(type)
if (forceArray) {
return `${caseCorrectedType}[]`
}
return caseCorrectedType
})
const allArrayTypes =
typeStrings.length > 1 && typeStrings.every(type => type.endsWith('[]'))
if (allArrayTypes) {
return `(${typeStrings.map(type => type.replace('[]', '')).join(' | ')})[]`
}
return typeStrings.join(' | ')
}
function getFPFnType(params, returns) {
const fpParams = params.map(param => param.type.names)
const arity = fpParams.length
fpParams.push(returns)
return `CurriedFn${arity}<${fpParams.map(getType).join(', ')}>`
}
module.exports = {
correctTypeCase,
getParams,
getType,
getFPFnType
}