Skip to content

Commit

Permalink
wbotelhos#243 Implements raty/core module
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrey Bukhtiyarov committed Oct 15, 2022
1 parent 1f170c3 commit 4ae0b3c
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
9 changes: 9 additions & 0 deletions core/index.ts
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'
64 changes: 64 additions & 0 deletions core/store.ts
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,
}
}

0 comments on commit 4ae0b3c

Please sign in to comment.