Merge pull request #2781 from sveltejs/gh-2780

handle non-falsy non-function deriver return values
pull/2785/head
Rich Harris 5 years ago committed by GitHub
commit 9a564eddaa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,4 +1,4 @@
import { run_all, noop, safe_not_equal } from './internal/utils';
import { run_all, noop, safe_not_equal, is_function } from './internal/utils';
type Subscriber<T> = (value: T) => void;
@ -102,7 +102,7 @@ export function derived<T, S extends Stores>(
if (auto) {
set(result as T);
} else {
cleanup = result as Unsubscriber || noop;
cleanup = is_function(result) ? result as Unsubscriber : noop;
}
};

@ -1,5 +1,5 @@
import * as assert from 'assert';
import { readable, writable, derived, get } from '../store';
import { readable, writable, derived, get } from '../../store';
describe('store', () => {
describe('writable', () => {
@ -243,6 +243,30 @@ describe('store', () => {
assert.deepEqual(cleaned_up, [2, 3, 4]);
});
it('discards non-function return values', () => {
const num = writable(1);
const values = [];
const d = derived(num, ($num, set) => {
set($num * 2);
return {};
});
num.set(2);
const unsubscribe = d.subscribe(value => {
values.push(value);
});
num.set(3);
num.set(4);
assert.deepEqual(values, [4, 6, 8]);
unsubscribe();
});
it('allows derived with different types', () => {
const a = writable('one');
const b = writable(1);

@ -2,6 +2,6 @@ const glob = require("tiny-glob/sync.js");
require("./setup");
glob("*/index.js", { cwd: "test" }).forEach(function(file) {
glob("*/index.{js,ts}", { cwd: "test" }).forEach(function(file) {
require("./" + file);
});
Loading…
Cancel
Save