forked from blakeembrey/code-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonce.js
More file actions
21 lines (18 loc) · 656 Bytes
/
Copy pathonce.js
File metadata and controls
21 lines (18 loc) · 656 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
module.exports = function (fn, times) {
// Set times to one if nothing is passed through and keep track of the
// latest return value to return when we run out of execution times.
var memo;
times = times || 1;
// Return the function that will be executed.
return function () {
if (!times) { return memo; }
// Set memo to the result of the function and decrement the number of
// executions.
memo = fn.apply(this, arguments);
times -= 1;
// If there are no more execution times, set the function to `null` so
// it can be garbage collected and return the memo.
times || (fn = null);
return memo;
};
};