Skip to content

Instantly share code, notes, and snippets.

@js2me
Created April 30, 2020 10:05
Show Gist options
  • Save js2me/2e509d6f9a4060960d1bc0607793bbb2 to your computer and use it in GitHub Desktop.
Save js2me/2e509d6f9a4060960d1bc0607793bbb2 to your computer and use it in GitHub Desktop.
createMemoContainer
/**
*
* @param initialValue {T} initial value
* @param callback {function} used to update value
*/
export const createMemoContainer = <T, ExtraArgs extends unknown[] = []>(
initialValue: T,
callback: (currentValue: T, ...args: ExtraArgs) => T | null,
): ((...args: ExtraArgs) => T) => {
let currentValue: T = initialValue;
return (...args: ExtraArgs): T => {
const newValue = callback(currentValue, ...args);
if (newValue === null) return currentValue;
currentValue = newValue;
return newValue;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment