Skip to content

Instantly share code, notes, and snippets.

@ktsn
Created July 2, 2016 13:19
Show Gist options
  • Save ktsn/cbc76511a1fa879fd3d7da1c77c56eb7 to your computer and use it in GitHub Desktop.
Save ktsn/cbc76511a1fa879fd3d7da1c77c56eb7 to your computer and use it in GitHub Desktop.
type Subscriber<T> = (val: T) => void
type Unsubscriber = () => void
export default class Observable<T> {
private subscribers: Subscriber<T>[] = []
private unsubscriber: Unsubscriber
private _value: T
constructor(source?: (cb: Subscriber<T>) => Unsubscriber) {
if (source) {
this.unsubscriber = source(val => {
this.value = val
})
}
}
set value(val: T) {
this._value = val
this.subscribers.map(f => f(val))
}
get value() : T {
return this._value
}
subscribe(f: Subscriber<T>) : void {
this.subscribers.push(f)
}
unsubscribe() : void {
if (this.unsubscriber) {
this.unsubscriber()
}
this.subscribers = []
}
map<U>(f: (val: T) => U) : Observable<U> {
const o = new Observable<U>()
this.subscribe(val => {
o.value = f(val)
})
return o
}
filter(f: (val: T) => boolean) : Observable<T> {
const o = new Observable<T>()
this.subscribe(val => {
if (f(val)) {
o.value = val
}
})
return o
}
buffer(ms: number) : Observable<T[]> {
const o = new Observable<T[]>()
let timer: number = null
let buffer: T[] = []
this.subscribe(val => {
clearTimeout(timer)
buffer.push(val)
timer = setTimeout(() => {
o.value = buffer
buffer = []
}, ms)
})
return o
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment