forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.mjs
105 lines (85 loc) · 2.06 KB
/
store.mjs
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { run_all, noop } from './internal';
export function readable(start, value) {
const subscribers = [];
let stop;
function set(newValue) {
if (newValue === value) return;
value = newValue;
subscribers.forEach(s => s[1]());
subscribers.forEach(s => s[0](value));
}
return {
subscribe(run, invalidate = noop) {
if (subscribers.length === 0) {
stop = start(set);
}
const subscriber = [run, invalidate];
subscribers.push(subscriber);
run(value);
return function() {
const index = subscribers.indexOf(subscriber);
if (index !== -1) subscribers.splice(index, 1);
if (subscribers.length === 0) {
stop && stop();
stop = null;
}
};
}
};
}
export function writable(value, start = noop) {
let stop;
const subscribers = [];
function set(newValue) {
if (newValue === value) return;
value = newValue;
subscribers.forEach(s => s[1]());
subscribers.forEach(s => s[0](value));
}
function update(fn) {
set(fn(value));
}
function subscribe(run, invalidate = noop) {
const subscriber = [run, invalidate];
subscribers.push(subscriber);
if (subscribers.length === 1) stop = start() || noop;
run(value);
return () => {
const index = subscribers.indexOf(subscriber);
if (index !== -1) subscribers.splice(index, 1);
if (subscribers.length === 0) stop();
};
}
return { set, update, subscribe };
}
export function derive(stores, fn) {
const single = !Array.isArray(stores);
if (single) stores = [stores];
const auto = fn.length < 2;
let value = {};
return readable(set => {
let inited = false;
const values = [];
let pending = 0;
const sync = () => {
if (pending) return;
const result = fn(single ? values[0] : values, set);
if (auto && (value !== (value = result))) set(result);
}
const unsubscribers = stores.map((store, i) => store.subscribe(
value => {
values[i] = value;
pending &= ~(1 << i);
if (inited) sync();
},
() => {
pending |= (1 << i);
})
);
inited = true;
sync();
return function stop() {
run_all(unsubscribers);
};
});
}