Skip to content

Instantly share code, notes, and snippets.

@saiashirwad
Created November 4, 2023 07:49
Show Gist options
  • Save saiashirwad/0b28aef36b76b27b8ed622b726403016 to your computer and use it in GitHub Desktop.
Save saiashirwad/0b28aef36b76b27b8ed622b726403016 to your computer and use it in GitHub Desktop.
export function optimisticallyUpdateArray<Data>(
condition: (data: Data) => boolean,
replacement: Data | ((data: Data) => Data),
) {
return (data: Data[] | undefined) => {
if (!data) return data
const index = data.findIndex(condition)
if (index === -1) return data
const newData = [...data]
newData.splice(
index,
1,
typeof replacement === 'function'
? // @ts-ignore
replacement(data[index])
: replacement,
)
return newData
}
}
export function optimisticallyUpdateObject<Data>(
condition: (data: Data) => boolean,
replacement: Data | ((data: Data) => Data),
) {
return (data: Data | undefined) => {
if (!data) return data
if (!condition(data)) return data
return typeof replacement === 'function'
? // @ts-ignore
replacement(data)
: replacement
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment