Chapter 2, Thinking Functionally – A First Example
2.1 No extra variables: We can make do by using the fn
variable itself as a flag. After calling fn()
, we set the variable to null
. Before calling fn()
, we check that it’s not null
by using the short-circuit &&
operator:
// question_02_no_extra_variables.ts const once = <FNType extends (...args: any[]) => any>( fn: FNType | null ) => ((...args: Parameters<FNType>) => { fn && fn(...args); fn = null; }) as FNType;
We need a small change to let TypeScript know that fn
could be null
; otherwise, it would object to the fn =
null
assignment.
2.2 Alternating functions: Like what we did in the previous question, we swap functions, and then we do the call. Here, we use a destructuring assignment to write the swap more compactly. For more information, refer to developer.mozilla.org/en-US/docs/Web/JavaScript...