consistently handle falsy store values for derived, add tests

pull/7947/head
Simon Holthausen 3 years ago
parent 5eb2767afd
commit 1581da2e08

@ -69,7 +69,7 @@ export function validate_store(store, name) {
export function subscribe(store, ...callbacks) { export function subscribe(store, ...callbacks) {
if (store == null) { if (store == null) {
for (const callback of callbacks) { for (const callback of callbacks) {
callback(store); callback(undefined);
} }
return noop; return noop;
} }

@ -165,8 +165,9 @@ export function derived<S extends Stores, T>(
export function derived<T>(stores: Stores, fn: Function, initial_value?: T): Readable<T> { export function derived<T>(stores: Stores, fn: Function, initial_value?: T): Readable<T> {
const single = !Array.isArray(stores); const single = !Array.isArray(stores);
const stores_array: Array<Readable<any>> = single const stores_array: Array<Readable<any>> = single
? [stores as Readable<any>] // Fall back to readable() for falsy stores in array, else derived store will be forever pending
: stores as Array<Readable<any>>; ? [(stores || readable()) as Readable<any>]
: (stores as Array<Readable<any>>).map(store => store || readable());
const auto = fn.length < 2; const auto = fn.length < 2;

@ -428,6 +428,39 @@ describe('store', () => {
a.set(false); a.set(false);
assert.equal(b_started, false); assert.equal(b_started, false);
}); });
it('works with undefined stores #1', () => {
const a = derived(null, (n) => {
return n;
});
const values = [];
const unsubscribe = a.subscribe((value) => values.push(value));
unsubscribe();
assert.deepEqual(values, [undefined]);
});
it('works with undefined stores #2', () => {
const a = writable(1);
const b = derived([a, null, undefined], ([n, un1, un2]) => {
assert.equal(un1, undefined);
assert.equal(un2, undefined);
return n * 2;
});
const values = [];
const unsubscribe = b.subscribe(value => {
values.push(value);
});
a.set(2);
assert.deepEqual(values, [2, 4]);
unsubscribe();
a.set(3);
assert.deepEqual(values, [2, 4]);
});
}); });
describe('get', () => { describe('get', () => {

Loading…
Cancel
Save