-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction.js
31 lines (28 loc) · 802 Bytes
/
function.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
(function() {
'use strict';
if (! (Function.prototype.once instanceof Function)) {
const funcs = new WeakMap();
/**
* @see https://github.com/tc39/proposal-function-once
*/
Function.prototype.once = function once(thisArg) {
const callback = this;
return function(...args) {
if (funcs.has(callback)) {
return funcs.get(callback);
} else if (callback.constructor.name === 'AsyncFunction') {
const retVal = callback.apply(thisArg || callback, args).catch(err => {
funcs.delete(callback);
throw err;
});
funcs.set(callback, retVal);
return retVal;
} else if (callback instanceof Function) {
const retVal = callback.apply(thisArg || callback, args);
funcs.set(callback, retVal);
return retVal;
}
};
};
}
})();