Skip to content

Commit

Permalink
Merge pull request #2781 from sveltejs/gh-2780
Browse files Browse the repository at this point in the history
handle non-falsy non-function deriver return values
  • Loading branch information
Rich-Harris authored May 16, 2019
2 parents 5d690f8 + 0b12b89 commit 9a564ed
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/store.ts
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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;
}
};

Expand Down
26 changes: 25 additions & 1 deletion test/store.ts → test/store/index.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

0 comments on commit 9a564ed

Please sign in to comment.