Skip to content

Commit 61bcf81

Browse files
committed
feat: add array with length prop type validator
1 parent f776229 commit 61bcf81

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

src/arrayWithLength.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import propTypes from 'prop-types'
2+
3+
const arrayWithLengthFactory = ({
4+
min = 0,
5+
max = Infinity,
6+
propType,
7+
isRequired,
8+
}) => (props, propName, componentName) => {
9+
const arr = props[propName]
10+
11+
if (isRequired && typeof arr === 'undefined') {
12+
return new Error(`${propName} is required.`)
13+
}
14+
15+
if (arr && !Array.isArray(arr)) {
16+
return new Error(`${propName} is not an array.`)
17+
}
18+
19+
if (arr && arr.length > max) {
20+
return new Error(
21+
// prettier-ignore
22+
`${propName} array has a length of ${arr.length}, but the maximum is ${max}`
23+
)
24+
}
25+
26+
if (arr && arr.length < min) {
27+
return new Error(
28+
// prettier-ignore
29+
`${propName} array has a length of ${arr.length}, but the minimum is ${min}`
30+
)
31+
}
32+
33+
if (arr && propType) {
34+
const len = arr.length
35+
for (let i = 0; i < len; i++) {
36+
propTypes.checkPropTypes(
37+
{
38+
[i]: propType,
39+
},
40+
arr,
41+
propName,
42+
componentName
43+
)
44+
}
45+
}
46+
47+
return null
48+
}
49+
50+
export const arrayWithLength = (min, max, propType) => {
51+
const fn = arrayWithLengthFactory({ min, max, propType, isRequired: false })
52+
fn.isRequired = arrayWithLengthFactory({
53+
min,
54+
max,
55+
propType,
56+
isRequired: true,
57+
})
58+
return fn
59+
}

src/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1+
export { arrayWithLength } from './arrayWithLength'
12
export { instanceOfComponent } from './instanceOfComponent'
23
export { mutuallyExclusive } from './mutuallyExclusive'

0 commit comments

Comments
 (0)