Skip to content

Instantly share code, notes, and snippets.

@forivall
Last active December 9, 2023 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forivall/6636f8e032450168a61240527184879e to your computer and use it in GitHub Desktop.
Save forivall/6636f8e032450168a61240527184879e to your computer and use it in GitHub Desktop.
Fastest and smallest once wrapper in js
const unit = <T>(value: T) => () => value;
const lazy = <T>(fn: () => T) => {
let f = (): T => (f = unit(fn()))();
return () => f();
};
const lazyWithReset = <T>(fn: () => T) => {
let f: () => T;
const reset = () => {
f = () => (f = unit(fn()))();
}
reset();
return Object.assign(() => f(), { reset });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment