99c5fc1cb4fe973270709368c480997e0b739a00
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / onetime / index.js
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 };