Last change
on this file since 6a3a178 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1.1 KB
|
Line | |
---|
1 | 'use strict';
|
---|
2 | const mimicFn = require('mimic-fn');
|
---|
3 |
|
---|
4 | const calledFunctions = new WeakMap();
|
---|
5 |
|
---|
6 | const onetime = (function_, options = {}) => {
|
---|
7 | if (typeof function_ !== 'function') {
|
---|
8 | throw new TypeError('Expected a function');
|
---|
9 | }
|
---|
10 |
|
---|
11 | let returnValue;
|
---|
12 | let callCount = 0;
|
---|
13 | const functionName = function_.displayName || function_.name || '<anonymous>';
|
---|
14 |
|
---|
15 | const onetime = function (...arguments_) {
|
---|
16 | calledFunctions.set(onetime, ++callCount);
|
---|
17 |
|
---|
18 | if (callCount === 1) {
|
---|
19 | returnValue = function_.apply(this, arguments_);
|
---|
20 | function_ = null;
|
---|
21 | } else if (options.throw === true) {
|
---|
22 | throw new Error(`Function \`${functionName}\` can only be called once`);
|
---|
23 | }
|
---|
24 |
|
---|
25 | return returnValue;
|
---|
26 | };
|
---|
27 |
|
---|
28 | mimicFn(onetime, function_);
|
---|
29 | calledFunctions.set(onetime, callCount);
|
---|
30 |
|
---|
31 | return onetime;
|
---|
32 | };
|
---|
33 |
|
---|
34 | module.exports = onetime;
|
---|
35 | // TODO: Remove this for the next major release
|
---|
36 | module.exports.default = onetime;
|
---|
37 |
|
---|
38 | module.exports.callCount = function_ => {
|
---|
39 | if (!calledFunctions.has(function_)) {
|
---|
40 | throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
|
---|
41 | }
|
---|
42 |
|
---|
43 | return calledFunctions.get(function_);
|
---|
44 | };
|
---|
Note:
See
TracBrowser
for help on using the repository browser.