How to derive a store that contains a list of stores in svelte

96 Views Asked by At

I have a store that contains a list of derived stores in svelte. (I know this might not be the best but humor me). How can I create a store that gives the inner values? I came up with this function:

const deriveListOfStores = <T>(stores: Readable<Readable<T>[]>) => {
    const state = writable<T[]>([]);

    const unsubscribes = new Set<() => void>();

    const subscribers = new Set<(v: T[]) => void>();

    return {
        subscribe: (cb: (v: T[]) => void) => {
            subscribers.add(cb);

            if (subscribers.size === 1) {
                unsubscribes.add(
                    stores.subscribe((storesValue) => {
                        storesValue.forEach((store, storeIndex) => {
                            unsubscribes.add(
                                store.subscribe((v) => {
                                    state.update((s) => {
                                        s[storeIndex] = v;
            
                                        return s;
                                    });
                                })
                            );
                        });
                    })
                );
            }

            const unsub = state.subscribe(cb);

            return () => {
                subscribers.delete(cb);
                unsub();

                if (subscribers.size === 0) {
                    unsubscribes.forEach((u) => u());
                    unsubscribes.clear();
                }
            }
        }
    }
};

which I need to test extensively, but it seems like their should be an easier way to do this? It may be that the assumption is that if I need this I am off my rocker which I am willing to except but if there is a better way to do this (some kind of built in function, 3rd party lib, or maybe I'm overcomplicating this function severely) I would like to know. Thanks so much!

0

There are 0 best solutions below