Created
July 2, 2016 13:19
-
-
Save ktsn/cbc76511a1fa879fd3d7da1c77c56eb7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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