Created
August 23, 2022 08:23
-
-
Save RavenHursT/a425673c4a5537ccc4f464949041cdf6 to your computer and use it in GitHub Desktop.
Array mutation utility methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const replaceItemInList = ( | |
item: unknown, | |
list: unknown[], | |
index: number | |
) => [ | |
...list.slice(0, index), | |
item, | |
...list.slice(index + 1) | |
] | |
export const removeItemByIndex = (list: unknown[], index: number) => [ | |
...list.slice(0, index), | |
...list.slice(index + 1) | |
] | |
export const findAndReplaceItemInList = (item: unknown, list: unknown[]) => { | |
const itemIndex = list.indexOf(item) | |
return itemIndex >= 0 ? | |
replaceItemInList( | |
item, | |
list, | |
list.indexOf(item) | |
) : list | |
} | |
export const findAndRemoveItemInList = ( | |
item: unknown, | |
list: unknown[] | |
) => { | |
const itemIndex = list.indexOf(item) | |
return itemIndex >= 0 ? removeItemByIndex( | |
list, | |
list.indexOf(item) | |
) : list | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment