0
0
mirror of https://github.com/sveltejs/svelte.git synced 2024-12-01 17:30:59 +01:00

Merge pull request #2397 from sveltejs/derived-initial-value

add initial_value argument to derived store
This commit is contained in:
Rich Harris 2019-04-11 22:56:10 -04:00 committed by GitHub
commit ade0bc870a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 12 additions and 10 deletions

View File

@ -293,13 +293,13 @@ const time = readable(new Date(), set => {
store = derived(a, callback: (a: any) => any)
```
```js
store = derived(a, callback: (a: any, set: (value: any) => void) => void)
store = derived(a, callback: (a: any, set: (value: any) => void) => void, initial_value: any)
```
```js
store = derived([a, ...b], callback: ([a: any, ...b: any[]]) => any)
```
```js
store = derived([a, ...b], callback: ([a: any, ...b: any[]], set: (value: any) => void) => void)
store = derived([a, ...b], callback: ([a: any, ...b: any[]], set: (value: any) => void) => void, initial_value: any)
```
---
@ -318,12 +318,14 @@ const doubled = derived(a, $a => $a * 2);
The callback can set a value asynchronously by accepting a second argument, `set`, and calling it when appropriate.
In this case, you can also pass a third argument to `derived` — the initial value of the derived store before `set` is first called.
```js
import { derived } from 'svelte/store';
const delayed = derived(a, ($a, set) => {
setTimeout(() => set($a), 1000);
});
}, 'one moment...');
```
---

View File

@ -39,14 +39,14 @@ export function writable(value, start = noop) {
return { set, update, subscribe };
}
export function derived(stores, fn) {
export function derived(stores, fn, initial_value) {
const single = !Array.isArray(stores);
if (single) stores = [stores];
const auto = fn.length < 2;
let value = {};
return readable(undefined, set => {
return readable(initial_value, set => {
let inited = false;
const values = [];
@ -56,7 +56,7 @@ export function derived(stores, fn) {
if (pending) return;
const result = fn(single ? values[0] : values, set);
if (auto && (value !== (value = result))) set(result);
}
};
const unsubscribers = stores.map((store, i) => store.subscribe(
value => {

View File

@ -142,10 +142,10 @@ describe('store', () => {
});
it('passes optional set function', () => {
const number = writable(0);
const number = writable(1);
const evens = derived(number, (n, set) => {
if (n % 2 === 0) set(n);
});
}, 0);
const values = [];
@ -153,17 +153,17 @@ describe('store', () => {
values.push(value);
});
number.set(1);
number.set(2);
number.set(3);
number.set(4);
number.set(5);
assert.deepEqual(values, [0, 2, 4]);
unsubscribe();
number.set(5);
number.set(6);
number.set(7);
number.set(8);
assert.deepEqual(values, [0, 2, 4]);
});