forked from wbotelhos/raty
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
wbotelhos#243 Implements raty/core module
- Loading branch information
Andrey Bukhtiyarov
committed
Oct 15, 2022
1 parent
1f170c3
commit 4ae0b3c
Showing
2 changed files
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
export type { | ||
Observable, | ||
Observer, | ||
Subscription, | ||
RatyStore, | ||
RatyStoreOptions, | ||
} from "./store" | ||
export { create } from "./store" | ||
export * as Raty from './store' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
export interface Observable<A> { | ||
subscribe(observer: Observer<A>): Subscription | ||
} | ||
|
||
export interface Observer<A> { | ||
(value: A): void | ||
} | ||
|
||
export interface Subscription { | ||
unsubscribe(): void | ||
} | ||
|
||
export interface RatyStore extends Observable<number> { | ||
get(): number | ||
set(value: number): void | ||
set(modifier: ()=> number): void | ||
cancel(): void | ||
} | ||
|
||
export interface RatyStoreOptions { | ||
value: (() => number) | number | ||
} | ||
|
||
export function create(options: RatyStoreOptions): RatyStore { | ||
const initialValue = typeof options.value === 'function' ? options.value() : options.value | ||
let value = initialValue | ||
|
||
const listeners = new Set<Observer<number>>() | ||
|
||
const notify = () => { | ||
for (const listener of listeners) { | ||
listener(value) | ||
} | ||
} | ||
|
||
const set = (fa: (() => number) | number) => { | ||
const newValue = typeof fa === 'function' ? fa() : value | ||
|
||
if (newValue !== value) { | ||
value = newValue | ||
|
||
notify() | ||
} | ||
} | ||
|
||
const get = () => value | ||
|
||
const subscribe = (observer: Observer<number>): Subscription => { | ||
listeners.add(observer) | ||
|
||
return { | ||
unsubscribe: () => listeners.delete(observer) | ||
} | ||
} | ||
|
||
const cancel = () => set(initialValue) | ||
|
||
return { | ||
get, | ||
set, | ||
subscribe, | ||
cancel, | ||
} | ||
} |