Created
November 4, 2023 07:49
-
-
Save saiashirwad/0b28aef36b76b27b8ed622b726403016 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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