forked from final-form/final-form-arrays
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpop.js
37 lines (34 loc) · 880 Bytes
/
pop.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
// @flow
import type { MutableState, Mutator, Tools } from 'final-form'
import { escapeRegexTokens } from './utils'
const pop: Mutator<any> = (
[name]: any[],
state: MutableState<any>,
{ changeValue }: Tools<any>
) => {
let result
let removedIndex: ?number
changeValue(state, name, (array: ?(any[])): ?(any[]) => {
if (array) {
if (!array.length) {
return []
}
removedIndex = array.length - 1
result = array[removedIndex]
return array.slice(0, removedIndex)
}
})
// now we have to remove any subfields for our index,
if (removedIndex !== undefined) {
const pattern = new RegExp(
`^${escapeRegexTokens(name)}\\[${removedIndex}].*`
)
Object.keys(state.fields).forEach(key => {
if (pattern.test(key)) {
delete state.fields[key]
}
})
}
return result
}
export default pop