From 0edb5debf2d323afdc34d9aa933f18b42abff93a Mon Sep 17 00:00:00 2001 From: Richard Harris <richard.a.harris@gmail.com> Date: Thu, 16 May 2019 08:31:53 -0400 Subject: [PATCH] handle non-falsy non-function deriver return values - fixes #2780 --- src/store.ts | 4 ++-- test/{store.ts => store/index.ts} | 28 ++++++++++++++++++++++++++-- test/test.js | 2 +- 3 files changed, 29 insertions(+), 5 deletions(-) rename test/{store.ts => store/index.ts} (91%) diff --git a/src/store.ts b/src/store.ts index 462f155c2ada..1f00503af288 100644 --- a/src/store.ts +++ b/src/store.ts @@ -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; } }; diff --git a/test/store.ts b/test/store/index.ts similarity index 91% rename from test/store.ts rename to test/store/index.ts index f931a841d741..f0b6203dc9d9 100644 --- a/test/store.ts +++ b/test/store/index.ts @@ -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); @@ -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); diff --git a/test/test.js b/test/test.js index 993b1f637c51..380bbee30408 100644 --- a/test/test.js +++ b/test/test.js @@ -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); }); \ No newline at end of file