Skip to content

Commit

Permalink
handle non-falsy non-function deriver return values - fixes #2780
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed May 16, 2019
1 parent 5121a3c commit 0edb5de
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 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
28 changes: 26 additions & 2 deletions test/store.ts → test/store/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as assert from 'assert';
import { readable, writable, derived, get } from '../store';
import { readable, writable, derived, get } from '../../store';

describe('store', () => {
describe.only('store', () => {
describe('writable', () => {
it('creates a writable store', () => {
const count = writable(0);
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 0edb5de

Please sign in to comment.