Skip to content

Instantly share code, notes, and snippets.

@evanrs
Last active January 29, 2022 04:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanrs/91f2fbb203b046fc2b91bee6074ff56f to your computer and use it in GitHub Desktop.
Save evanrs/91f2fbb203b046fc2b91bee6074ff56f to your computer and use it in GitHub Desktop.
variadic once in typescript
type ArityNone<T> = () => T;
type ArityOne<T, A> = (a?: A) => T;
type ArityTwo<T, A, B> = (a: A, b?: B) => T;
type ArityThree<T, A, B, C> = (a: A, b: B, c?: C) => T;
type ArityFour<T, A, B, C, D> = (a: A, b: B, c: C, d?: D) => T;
export function once<T>(resolver: ArityNone<T>): ArityNone<T>;
export function once<T, A>(resolver: ArityOne<T, A>): ArityOne<T, A>;
export function once<T, A, B>(resolver: ArityTwo<T, A, B>): ArityTwo<T, A, B>;
export function once<T, A, B, C>(resolver: ArityThree<T, A, B, C>): ArityThree<T, A, B, C>;
export function once<T, A, B, C, D>(resolver: ArityFour<T, A, B, C, D>): ArityFour<T, A, B, C, D> {
let value: T;
let invoke = true;
return (a: A, b: B, c: C, d: D) => {
if (invoke) {
value = resolver(a, b, c, d);
invoke = false;
}
return value;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment