Skip to content

Commit b2260bc

Browse files
authored
refactor: migrate array to set for subscriberss (#6295)
1 parent 48934c8 commit b2260bc

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

src/runtime/store/index.ts

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -63,17 +63,16 @@ export function readable<T>(value?: T, start?: StartStopNotifier<T>): Readable<T
6363
*/
6464
export function writable<T>(value?: T, start: StartStopNotifier<T> = noop): Writable<T> {
6565
let stop: Unsubscriber;
66-
const subscribers: Array<SubscribeInvalidateTuple<T>> = [];
66+
const subscribers: Set<SubscribeInvalidateTuple<T>> = new Set();
6767

6868
function set(new_value: T): void {
6969
if (safe_not_equal(value, new_value)) {
7070
value = new_value;
7171
if (stop) { // store is ready
7272
const run_queue = !subscriber_queue.length;
73-
for (let i = 0; i < subscribers.length; i += 1) {
74-
const s = subscribers[i];
75-
s[1]();
76-
subscriber_queue.push(s, value);
73+
for (const subscriber of subscribers) {
74+
subscriber[1]();
75+
subscriber_queue.push(subscriber, value);
7776
}
7877
if (run_queue) {
7978
for (let i = 0; i < subscriber_queue.length; i += 2) {
@@ -91,18 +90,17 @@ export function writable<T>(value?: T, start: StartStopNotifier<T> = noop): Writ
9190

9291
function subscribe(run: Subscriber<T>, invalidate: Invalidator<T> = noop): Unsubscriber {
9392
const subscriber: SubscribeInvalidateTuple<T> = [run, invalidate];
94-
subscribers.push(subscriber);
95-
if (subscribers.length === 1) {
93+
subscribers.add(subscriber);
94+
if (subscribers.size === 1) {
9695
stop = start(set) || noop;
9796
}
9897
run(value);
9998

10099
return () => {
101-
const index = subscribers.indexOf(subscriber);
102-
if (index !== -1) {
103-
subscribers.splice(index, 1);
100+
if (subscribers.has(subscriber)) {
101+
subscribers.delete(subscriber);
104102
}
105-
if (subscribers.length === 0) {
103+
if (subscribers.size === 0) {
106104
stop();
107105
stop = null;
108106
}

0 commit comments

Comments
 (0)