Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/great-experts-enjoy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'formik': patch
---

Fix return types and add docs to standalone `FieldArray` utility exports (`move`, `swap`, `insert`, `replace`).
17 changes: 9 additions & 8 deletions packages/formik/src/FieldArray.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,50 +63,51 @@ export interface ArrayHelpers<T extends any[] = any[]> {
pop<X extends T[number] = T[number]>(): X | undefined;
}

/**
* Some array helpers!
*/
export const move = <T,>(array: T[], from: number, to: number) => {
/** Move an element in an array from one index to another. Returns a new array. */
export const move = <T,>(array: T[], from: number, to: number): T[] => {
const copy = copyArrayLike(array);
const value = copy[from];
copy.splice(from, 1);
copy.splice(to, 0, value);
return copy;
};

/** Swap two elements in an array by index. Returns a new array. */
export const swap = <T,>(
arrayLike: ArrayLike<T>,
indexA: number,
indexB: number
) => {
): T[] => {
const copy = copyArrayLike(arrayLike);
const a = copy[indexA];
copy[indexA] = copy[indexB];
copy[indexB] = a;
return copy;
};

/** Insert an element at the given index. Returns a new array. */
export const insert = <T,>(
arrayLike: ArrayLike<T>,
index: number,
value: T
) => {
): T[] => {
const copy = copyArrayLike(arrayLike);
copy.splice(index, 0, value);
return copy;
};

/** Replace the element at the given index. Returns a new array. */
export const replace = <T,>(
arrayLike: ArrayLike<T>,
index: number,
value: T
) => {
): T[] => {
const copy = copyArrayLike(arrayLike);
copy[index] = value;
return copy;
};

const copyArrayLike = (arrayLike: ArrayLike<any>) => {
const copyArrayLike = <T,>(arrayLike: ArrayLike<T>): T[] => {
if (!arrayLike) {
return [];
} else if (Array.isArray(arrayLike)) {
Expand Down