-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwritable.js
More file actions
65 lines (65 loc) · 2.3 KB
/
Copy pathwritable.js
File metadata and controls
65 lines (65 loc) · 2.3 KB
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
65
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
exports.__esModule = true;
var Utils = __importStar(require("../utils"));
var subscriberQueue = [];
var Writable = /** @class */ (function () {
function Writable(value, start) {
if (start === void 0) { start = Utils.noop; }
this.stop = null;
this.subscribers = [];
this.value = value;
this.start = start;
}
Writable.prototype.get = function () {
return Utils.getStoreValue(this);
};
Writable.prototype.set = function (newValue) {
if (Utils.safeNotEqual(this.value, newValue)) {
this.value = newValue;
if (this.stop) {
var runQueue = !subscriberQueue.length;
for (var i = 0; i < this.subscribers.length; i += 1) {
var s = this.subscribers[i];
s[1]();
subscriberQueue.push(s, this.value);
}
if (runQueue) {
for (var i = 0; i < subscriberQueue.length; i += 2)
subscriberQueue[i][0](subscriberQueue[i + 1]);
subscriberQueue.length = 0;
}
}
}
};
Writable.prototype.update = function (callback) {
this.set(callback(this.value));
};
Writable.prototype.subscribe = function (run, invalidate) {
var _this = this;
if (invalidate === void 0) { invalidate = Utils.noop; }
var subscriber = [run, invalidate];
this.subscribers.push(subscriber);
if (this.subscribers.length === 1)
this.stop = this.start(this.set) || Utils.noop;
Utils.run(this.value);
return function () {
var index = _this.subscribers.indexOf(subscriber);
if (index !== -1)
_this.subscribers.splice(index, 1);
if (_this.subscribers.length === 0) {
if (_this.stop)
_this.stop();
_this.stop = null;
}
};
};
return Writable;
}());
exports.Writable = Writable;