Run a function once in JavaScript
Wraps a function so it runs the first time and returns that result forever after.
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}
Keywords and builtins used here
functionifletreturnthis
The run, in numbers
- Lines
- 11
- Characters to type
- 162
- Tokens
- 49
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 29 seconds.
Step 2 of 4 in Closures, step 2 of 16 in Functions & patterns.