Skip to content

Instantly share code, notes, and snippets.

@RavenHursT
Created August 23, 2022 08:23
Show Gist options
  • Save RavenHursT/a425673c4a5537ccc4f464949041cdf6 to your computer and use it in GitHub Desktop.
Save RavenHursT/a425673c4a5537ccc4f464949041cdf6 to your computer and use it in GitHub Desktop.
Array mutation utility methods
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