Last active
January 29, 2022 04:43
-
-
Save evanrs/91f2fbb203b046fc2b91bee6074ff56f to your computer and use it in GitHub Desktop.
variadic once in typescript
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
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