This repository has been archived by the owner on Apr 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdisposable.js
64 lines (54 loc) · 1.77 KB
/
disposable.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
'use strict';
function noop () { }
var isFunction = module.exports = (function () {
var isFn = function (value) {
return typeof value === 'function' || false;
};
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value === 'function' &&
Object.prototype.toString.call(value) === '[object Function]';
};
}
return isFn;
}());
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} action Action to run during the first call to dispose.
* The action is guaranteed to be run at most once.
*/
function Disposable (action) {
this.isDisposed = false;
this.action = isFunction(action) ? action : noop;
}
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose.
* The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
Disposable._fixup = function (result) {
return Disposable.isDisposable(result) ? result : Disposable.empty;
};
module.exports = Disposable;