-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.ts
790 lines (728 loc) · 24.9 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
/**
* tansu is a lightweight, push-based state management library.
* It borrows the ideas and APIs originally designed and implemented by {@link https://github.com/sveltejs/rfcs/blob/master/text/0002-reactive-stores.md | Svelte stores}.
*
* @packageDocumentation
*/
declare global {
interface SymbolConstructor {
readonly observable: symbol;
}
}
const symbolObservable: typeof Symbol.observable =
(typeof Symbol === 'function' && Symbol.observable) || ('@@observable' as any);
/**
* A callback invoked when a store value changes. It is called with the latest value of a given store.
*/
export type SubscriberFunction<T> = (value: T) => void;
/**
* A partial {@link https://github.com/tc39/proposal-observable#api | observer} notified when a store value changes. A store will call the {@link SubscriberObject.next | next} method every time the store's state is changing.
*/
export interface SubscriberObject<T> {
/**
* A store will call this method every time the store's state is changing.
*/
next: SubscriberFunction<T>;
/**
* Unused, only declared for compatibility with rxjs.
*/
error?: any;
/**
* Unused, only declared for compatibility with rxjs.
*/
complete?: any;
/**
* A store will call this method when it knows that the value will be changed.
* A call to this method will be followed by a call to {@link SubscriberObject.next | next} or to {@link SubscriberObject.resume | resume}.
*/
pause: () => void;
/**
* A store will call this method if {@link SubscriberObject.pause | pause} was called previously
* and the value finally did not need to change.
*/
resume: () => void;
}
interface PrivateSubscriberObject<T> extends SubscriberObject<T> {
_value: T;
_valueIndex: number;
}
/**
* Expresses interest in store value changes over time. It can be either:
* - a callback function: {@link SubscriberFunction};
* - a partial observer: {@link SubscriberObject}.
*/
export type Subscriber<T> = SubscriberFunction<T> | Partial<SubscriberObject<T>> | null | undefined;
/**
* A function to unsubscribe from value change notifications.
*/
export type UnsubscribeFunction = () => void;
/**
* An object with the `unsubscribe` method.
* Subscribable stores might choose to return such object instead of directly returning {@link UnsubscribeFunction} from a subscription call.
*/
export interface UnsubscribeObject {
/**
* A method that acts as the {@link UnsubscribeFunction}.
*/
unsubscribe: UnsubscribeFunction;
}
export type Unsubscriber = UnsubscribeObject | UnsubscribeFunction;
/**
* Represents a store accepting registrations (subscribers) and "pushing" notifications on each and every store value change.
*/
export interface SubscribableStore<T> {
/**
* A method that makes it possible to register "interest" in store value changes over time.
* It is called each and every time the store's value changes.
* A registered subscriber is notified synchronously with the latest store value.
*
* @param subscriber - a subscriber in a form of a {@link SubscriberFunction} or a {@link SubscriberObject}. Returns a {@link Unsubscriber} (function or object with the `unsubscribe` method) that can be used to unregister and stop receiving notifications of store value changes.
* @returns The {@link UnsubscribeFunction} or {@link UnsubscribeObject} that can be used to unsubscribe (stop state change notifications).
*/
subscribe(subscriber: Subscriber<T>): Unsubscriber;
}
/**
* This interface augments the base {@link SubscribableStore} interface with the Angular-specific `OnDestroy` callback. The {@link Readable} stores can be registered in the Angular DI container and will automatically discard all the subscription when a given store is destroyed.
*/
export interface Readable<T> extends SubscribableStore<T> {
subscribe(subscriber: Subscriber<T>): UnsubscribeFunction & UnsubscribeObject;
[Symbol.observable](): Readable<T>;
}
/**
* A function that can be used to update store's value. This function is called with the current value and should return new store value.
*/
export type Updater<T> = (value: T) => T;
/**
* Builds on top of {@link Readable} and represents a store that can be manipulated from "outside": anyone with a reference to writable store can either update or completely replace state of a given store.
*
* @example
*
* ```typescript
* // reset counter's store value to 0 by using the {@link Writable.set} method
* counterStore.set(0);
*
* // increment counter's store value by using the {@link Writable.update} method
* counterStore.update(currentValue => currentValue + 1);
* ```
*/
export interface Writable<T> extends Readable<T> {
/**
* Replaces store's state with the provided value.
* @param value - value to be used as the new state of a store.
*/
set(value: T): void;
/**
* Updates store's state by using an {@link Updater} function.
* @param updater - a function that takes the current state as an argument and returns the new state.
*/
update(updater: Updater<T>): void;
}
const noop = () => {};
const bind = <T>(object: T | null | undefined, fnName: keyof T) => {
const fn = object ? object[fnName] : null;
return typeof fn === 'function' ? fn.bind(object) : noop;
};
const toSubscriberObject = <T>(subscriber: Subscriber<T>): PrivateSubscriberObject<T> =>
typeof subscriber === 'function'
? {
next: subscriber.bind(null),
pause: noop,
resume: noop,
_value: undefined as any,
_valueIndex: 0,
}
: {
next: bind(subscriber, 'next'),
pause: bind(subscriber, 'pause'),
resume: bind(subscriber, 'resume'),
_value: undefined as any,
_valueIndex: 0,
};
const returnThis = function <T>(this: T): T {
return this;
};
/**
* Returns a wrapper (for the given store) which only exposes the {@link Readable} interface.
* This allows to easily expose any store as read-only.
*
* @param store - store to wrap
* @returns A wrapper which only exposes the {@link Readable} interface.
*/
export function asReadable<T>(store: Readable<T>): Readable<T> {
return {
subscribe: store.subscribe.bind(store),
[symbolObservable]: returnThis,
};
}
const queueProcess = Symbol();
let willProcessQueue = false;
const queue = new Set<{ [queueProcess](): void }>();
const callUnsubscribe = (unsubscribe: Unsubscriber) =>
typeof unsubscribe === 'function' ? unsubscribe() : unsubscribe.unsubscribe();
/**
* Batches multiple changes to stores while calling the provided function,
* preventing derived stores from updating until the function returns,
* to avoid unnecessary recomputations.
*
* @remarks
*
* If a store is updated multiple times in the provided function, listeners
* of that store will only be called once when the provided function returns.
*
* It is possible to have nested calls of batch, in which case only the first
* (outer) call has an effect, inner calls only call the provided function.
*
* @param fn - a function that can update stores. Its return value is
* returned by the batch function.
*
* @example
* Using batch in the following example prevents logging the intermediate "Sherlock Lupin" value.
*
* ```typescript
* const firstName = writable('Arsène');
* const lastName = writable('Lupin');
* const fullName = derived([firstName, lastName], ([a, b]) => `${a} ${b}`);
* fullName.subscribe((name) => console.log(name)); // logs any change to fullName
* batch(() => {
* firstName.set('Sherlock');
* lastName.set('Holmes');
* });
* ```
*/
export const batch = <T>(fn: () => T): T => {
const needsProcessQueue = !willProcessQueue;
if (needsProcessQueue) {
willProcessQueue = true;
}
try {
return fn();
} finally {
if (needsProcessQueue) {
for (const store of queue) {
queue.delete(store);
store[queueProcess]();
}
willProcessQueue = false;
}
}
};
/**
* A utility function to get the current value from a given store.
* It works by subscribing to a store, capturing the value (synchronously) and unsubscribing just after.
*
* @param store - a store from which the current value is retrieved.
*
* @example
* ```typescript
* const myStore = writable(1);
* console.log(get(myStore)); // logs 1
* ```
*/
export function get<T>(store: SubscribableStore<T>): T {
let value: T;
callUnsubscribe(store.subscribe((v) => (value = v)));
return value!;
}
/**
* Base class that can be extended to easily create a custom {@link Readable} store.
*
* @example
* ```typescript
* class CounterStore extends Store {
* constructor() {
* super(1); // initial value
* }
*
* reset() {
* this.set(0);
* }
*
* increment() {
* this.update(value => value + 1);
* }
* }
*
* const store = new CounterStore(1);
*
* // logs 1 (initial value) upon subscription
* const unsubscribe = store.subscribe((value) => {
* console.log(value);
* });
* store.increment(); // logs 2
* store.reset(); // logs 0
*
* unsubscribe(); // stops notifications and corresponding logging
* ```
*/
export abstract class Store<T> implements Readable<T> {
private _subscribers = new Set<PrivateSubscriberObject<T>>();
private _cleanupFn: null | Unsubscriber = null;
private _subscribersPaused = false;
private _valueIndex = 1;
/**
*
* @param _value - Initial value of the store
*/
constructor(private _value: T) {}
private _start() {
this._cleanupFn = this.onUse() || noop;
}
private _stop() {
const cleanupFn = this._cleanupFn;
if (cleanupFn) {
this._cleanupFn = null;
callUnsubscribe(cleanupFn);
}
}
private [queueProcess](): void {
this._subscribersPaused = false;
const valueIndex = this._valueIndex;
const value = this._value;
const notEqualCache = {
[valueIndex]: false, // the subscriber already has the last value
[valueIndex - 1]: true, // the subscriber had the previous value,
// which is known to be different because notEqual is called in the set method
};
for (const subscriber of [...this._subscribers]) {
let different = notEqualCache[subscriber._valueIndex];
if (different == null) {
different = this.notEqual(subscriber._value, value);
notEqualCache[subscriber._valueIndex] = different;
}
if (different) {
subscriber._valueIndex = valueIndex;
subscriber._value = value;
subscriber.next(value);
} else {
subscriber._valueIndex = valueIndex;
subscriber.resume();
}
}
}
/**
* Compares two values and returns true if they are different.
* It is called when setting a new value to avoid doing anything
* (such as notifying listeners) if the value did not change.
* The default logic is to return true if `a` is a function or an object,
* or if `a` and `b` are different according to `Object.is`.
* This method can be overridden by subclasses to change the logic.
*
* @param a - First value to compare.
* @param b - Second value to compare.
* @returns true if a and b are considered different.
*/
protected notEqual(a: T, b: T): boolean {
const tOfA = typeof a;
if (tOfA !== 'function' && tOfA !== 'object') {
return !Object.is(a, b);
}
return true;
}
/**
* Puts the store in the paused state, which means it will soon update its value.
*
* @remarks
*
* The paused state prevents derived stores (both direct and transitive) from recomputing their value
* using the current value of this store.
*
* There are two ways to put a store back into its normal state: calling {@link Store.set | set} to set a new
* value or calling {@link Store.resumeSubscribers | resumeSubscribers} to declare that finally the value does not need to be
* changed.
*
* Note that a store should not stay in the paused state for a long time, and most of the time
* it is not needed to call pauseSubscribers or resumeSubscribers manually.
*
*/
protected pauseSubscribers(): void {
if (!this._subscribersPaused) {
this._subscribersPaused = true;
for (const subscriber of [...this._subscribers]) {
subscriber.pause();
}
}
}
/**
* Puts the store back to the normal state without changing its value, if it was in the paused state
* (cf {@link Store.pauseSubscribers | pauseSubscribers}).
*
* @remarks
*
* Does nothing if the store was not in the paused state.
*/
protected resumeSubscribers(): void {
if (this._subscribersPaused) {
batch(() => {
queue.add(this as any);
});
}
}
/**
* Replaces store's state with the provided value.
* Equivalent of {@link Writable.set}, but internal to the store.
*
* @param value - value to be used as the new state of a store.
*/
protected set(value: T): void {
if (this.notEqual(this._value, value)) {
this._valueIndex++;
this._value = value;
if (!this._cleanupFn) {
// subscriber not yet initialized
return;
}
this.pauseSubscribers();
}
this.resumeSubscribers();
}
/**
* Updates store's state by using an {@link Updater} function.
* Equivalent of {@link Writable.update}, but internal to the store.
*
* @param updater - a function that takes the current state as an argument and returns the new state.
*/
protected update(updater: Updater<T>): void {
this.set(updater(this._value));
}
/**
* Function called when the number of subscribers changes from 0 to 1
* (but not called when the number of subscribers changes from 1 to 2, ...).
* If a function is returned, it will be called when the number of subscribers changes from 1 to 0.
*
* @example
*
* ```typescript
* class CustomStore extends Store {
* onUse() {
* console.log('Got the fist subscriber!');
* return () => {
* console.log('All subscribers are gone...');
* };
* }
* }
*
* const store = new CustomStore();
* const unsubscribe1 = store.subscribe(() => {}); // logs 'Got the fist subscriber!'
* const unsubscribe2 = store.subscribe(() => {}); // nothing is logged as we've got one subscriber already
* unsubscribe1(); // nothing is logged as we still have one subscriber
* unsubscribe2(); // logs 'All subscribers are gone...'
* ```
*/
protected onUse(): Unsubscriber | void {}
/**
* Default Implementation of the {@link SubscribableStore.subscribe}, not meant to be overridden.
* @param subscriber - see {@link SubscribableStore.subscribe}
*/
subscribe(subscriber: Subscriber<T>): UnsubscribeFunction & UnsubscribeObject {
const subscriberObject = toSubscriberObject(subscriber);
this._subscribers.add(subscriberObject);
if (this._subscribers.size == 1) {
this._start();
}
subscriberObject._valueIndex = this._valueIndex;
subscriberObject._value = this._value;
subscriberObject.next(this._value);
if (this._subscribersPaused) {
subscriberObject.pause();
}
const unsubscribe = () => {
const removed = this._subscribers.delete(subscriberObject);
subscriberObject.next = noop;
subscriberObject.pause = noop;
subscriberObject.resume = noop;
if (removed && this._subscribers.size === 0) {
this._stop();
}
};
unsubscribe.unsubscribe = unsubscribe;
return unsubscribe;
}
[symbolObservable](): this {
return this;
}
}
export interface OnUseArgument<T> {
(value: T): void;
set: (value: T) => void;
update: (updater: Updater<T>) => void;
}
/**
* Type of a function that is called when the number of subscribers changes from 0 to 1
* (but not called when the number of subscribers changes from 1 to 2, ...).
* If it returns a function, that function will be called when the number of subscribers changes from 1 to 0.
*/
export type OnUseFn<T> = (arg: OnUseArgument<T>) => void | Unsubscriber;
/**
* Store options that can be passed to {@link readable} or {@link writable}.
*/
export interface StoreOptions<T> {
/**
* A function that is called when the number of subscribers changes from 0 to 1
* (but not called when the number of subscribers changes from 1 to 2, ...).
* If it returns a function, that function will be called when the number of subscribers changes from 1 to 0.
*/
onUse?: OnUseFn<T>;
/**
* Custom function to compare two values, that should return true if they
* are different.
* It is called when setting a new value to avoid doing anything
* (such as notifying listeners) if the value did not change.
* The default logic (when this option is not present) is to return true
* if `a` is a function or an object, or if `a` and `b` are different
* according to `Object.is`.
*
* @param a - First value to compare.
* @param b - Second value to compare.
* @returns true if a and b are considered different.
*/
notEqual?: (a: T, b: T) => boolean;
}
const noopUnsubscribe = () => {};
noopUnsubscribe.unsubscribe = noopUnsubscribe;
/**
* A convenience function to create an optimized constant store (i.e. which never changes
* its value). It does not keep track of its subscribers.
* @param value - value of the store, which will never change
*/
function constStore<T>(value: T): Readable<T> {
return {
subscribe(subscriber: Subscriber<T>) {
toSubscriberObject(subscriber).next(value);
return noopUnsubscribe;
},
[symbolObservable]: returnThis,
};
}
class WritableStore<T> extends Store<T> implements Writable<T> {
constructor(value: T) {
super(value);
}
set(value: T): void {
super.set(value);
}
update(updater: Updater<T>) {
super.update(updater);
}
}
const applyStoreOptions = <T, S extends Store<T>>(store: S, options: StoreOptions<T>): S => {
const { onUse, notEqual } = options;
if (onUse) {
(store as any).onUse = function (this: Store<T>) {
const setFn = (v: T) => this.set(v);
setFn.set = setFn;
setFn.update = (updater: Updater<T>) => this.update(updater);
return onUse(setFn);
};
}
if (notEqual) {
(store as any).notEqual = function (this: Store<T>, a: T, b: T) {
return notEqual(a, b);
};
}
return store;
};
/**
* A convenience function to create {@link Readable} store instances.
* @param value - Initial value of a readable store.
* @param options - Either an object with {@link StoreOptions | store options}, or directly the onUse function.
* The onUse function is a function called when the number of subscribers changes from 0 to 1
* (but not called when the number of subscribers changes from 1 to 2, ...).
* If a function is returned, it will be called when the number of subscribers changes from 1 to 0.
*
* @example Sample with an onUse function
* ```typescript
* const clock = readable("00:00", setState => {
* const intervalID = setInterval(() => {
* const date = new Date();
* setState(`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`);
* }, 1000);
*
* return () => clearInterval(intervalID);
* });
* ```
*/
export function readable<T>(value: T, options: StoreOptions<T> | OnUseFn<T> = {}): Readable<T> {
if (typeof options === 'function') {
options = { onUse: options };
}
if (!options.onUse) {
// special optimized case
return constStore(value);
}
return asReadable(applyStoreOptions(new WritableStore(value), options));
}
/**
* A convenience function to create {@link Writable} store instances.
* @param value - initial value of a new writable store.
* @param options - Either an object with {@link StoreOptions | store options}, or directly the onUse function.
* The onUse function is a function called when the number of subscribers changes from 0 to 1
* (but not called when the number of subscribers changes from 1 to 2, ...).
* If a function is returned, it will be called when the number of subscribers changes from 1 to 0.
*
* @example
* ```typescript
* const x = writable(0);
*
* x.update(v => v + 1); // increment
* x.set(0); // reset back to the default value
* ```
*/
export function writable<T>(value: T, options: StoreOptions<T> | OnUseFn<T> = {}): Writable<T> {
if (typeof options === 'function') {
options = { onUse: options };
}
const store = applyStoreOptions(new WritableStore(value), options);
return {
...asReadable(store),
set: store.set.bind(store),
update: store.update.bind(store),
};
}
type SubscribableStores =
| SubscribableStore<any>
| readonly [SubscribableStore<any>, ...SubscribableStore<any>[]];
type SubscribableStoresValues<S> = S extends SubscribableStore<infer T>
? T
: { [K in keyof S]: S[K] extends SubscribableStore<infer T> ? T : never };
type SyncDeriveFn<T, S> = (values: SubscribableStoresValues<S>) => T;
interface SyncDeriveOptions<T, S> extends Omit<StoreOptions<T>, 'onUse'> {
derive: SyncDeriveFn<T, S>;
}
type AsyncDeriveFn<T, S> = (
values: SubscribableStoresValues<S>,
set: OnUseArgument<T>
) => Unsubscriber | void;
interface AsyncDeriveOptions<T, S> extends Omit<StoreOptions<T>, 'onUse'> {
derive: AsyncDeriveFn<T, S>;
}
type DeriveFn<T, S> = SyncDeriveFn<T, S> | AsyncDeriveFn<T, S>;
interface DeriveOptions<T, S> extends Omit<StoreOptions<T>, 'onUse'> {
derive: DeriveFn<T, S>;
}
function isSyncDeriveFn<T, S>(fn: DeriveFn<T, S>): fn is SyncDeriveFn<T, S> {
return fn.length <= 1;
}
export abstract class DerivedStore<
T,
S extends SubscribableStores = SubscribableStores
> extends Store<T> {
constructor(private _stores: S, initialValue: T) {
super(initialValue);
}
protected onUse(): Unsubscriber | void {
let initDone = false;
let pending = 0;
let changed = 0;
const stores = this._stores;
const isArray = Array.isArray(stores);
const storesArr = isArray
? (stores as readonly SubscribableStore<any>[])
: [stores as SubscribableStore<any>];
const dependantValues = new Array(storesArr.length);
let cleanupFn: null | Unsubscriber = null;
const callCleanup = () => {
const fn = cleanupFn;
if (fn) {
cleanupFn = null;
callUnsubscribe(fn);
}
};
const callDerive = () => {
if (initDone && !pending) {
if (changed) {
changed = 0;
callCleanup();
cleanupFn = this.derive(isArray ? dependantValues : dependantValues[0]) || noop;
}
this.resumeSubscribers();
}
};
const unsubscribers = storesArr.map((store, idx) =>
store.subscribe({
next: (v) => {
dependantValues[idx] = v;
changed |= 1 << idx;
pending &= ~(1 << idx);
callDerive();
},
pause: () => {
pending |= 1 << idx;
this.pauseSubscribers();
},
resume: () => {
pending &= ~(1 << idx);
callDerive();
},
})
);
initDone = true;
callDerive();
return () => {
callCleanup();
unsubscribers.forEach(callUnsubscribe);
};
}
protected abstract derive(values: SubscribableStoresValues<S>): Unsubscriber | void;
}
/**
* A convenience function to create a new store with a state computed from the latest values of dependent stores.
* Each time the state of one of the dependent stores changes, a provided derive function is called to compute a new, derived state.
*
* @param stores - a single store or an array of dependent stores
* @param options - either an object with store options including a derive function or directly the derive function itself.
* The derive function is used to compute a new state based on the latest values of dependent stores
*
* @example
* ```typescript
* const x$ = writable(2);
* const y$ = writable(3);
* const sum$ = derived([x$, $y], ([x, y]) => x + y);
*
* // will log 5 upon subscription
* sum$.subscribe((value) => {
* console.log(value)
* });
*
* x$.set(3); // will re-evaluate the `([x, y]) => x + y` function and log 6 as this is the new state of the derived store
* ```
*/
export function derived<T, S extends SubscribableStores>(
stores: S,
options: AsyncDeriveFn<T, S> | AsyncDeriveOptions<T, S>,
initialValue: T
): Readable<T>;
export function derived<T, S extends SubscribableStores>(
stores: S,
options: SyncDeriveFn<T, S> | SyncDeriveOptions<T, S>,
initialValue?: T
): Readable<T>;
export function derived<T, S extends SubscribableStores>(
stores: S,
options: DeriveFn<T, S> | DeriveOptions<T, S>,
initialValue?: T
): Readable<T> {
if (typeof options === 'function') {
options = { derive: options };
}
const { derive, ...opts } = options;
const Derived = isSyncDeriveFn(derive)
? class extends DerivedStore<T, S> {
protected derive(values: SubscribableStoresValues<S>) {
this.set(derive(values));
}
}
: class extends DerivedStore<T, S> {
protected derive(values: SubscribableStoresValues<S>) {
const setFn = (v: T) => this.set(v);
setFn.set = setFn;
setFn.update = (updater: Updater<T>) => this.update(updater);
return derive(values, setFn);
}
};
return asReadable(
applyStoreOptions(new Derived(stores, initialValue as any), {
...opts,
onUse: undefined /* setting onUse is not allowed from derived */,
})
);
}