Created
November 16, 2016 07:03
-
-
Save NetanelBasal/9f579cfbef56f1fc0e47d12f0c00ad31 to your computer and use it in GitHub Desktop.
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
class Observable { | |
constructor(functionThatThrowsValues) { | |
this._functionThatThrowsValues = functionThatThrowsValues; | |
} | |
subscribe(next, error, complete) { | |
if (typeof next === "function") { | |
return this._functionThatThrowsValues({ | |
next, | |
error: error || () => {}, | |
complete: complete || () => {} | |
}); | |
} | |
else { | |
return this._functionThatThrowsValues(next); | |
} | |
} | |
map(projectionFunction) { | |
return new Observable(observer => { | |
return this.subscribe({ | |
next(val) { observer.next(projectionFunction(val)) }, | |
error(e) { observer.error(e) } , | |
complete() { observer.complete() } | |
}); | |
}); | |
} | |
mergeMap(anotherFunctionThatThrowsValues) { | |
return new Observable(observer => { | |
return this.subscribe({ | |
next(val) { | |
anotherFunctionThatThrowsValues(val).subscribe({ | |
next(val) {observer.next(val)}, | |
error(e) { observer.error(e) } , | |
complete() { observer.complete() } | |
}); | |
}, | |
error(e) { observer.error(e) } , | |
complete() { observer.complete() } | |
}); | |
}); | |
} | |
static fromArray(array) { | |
return new Observable(observer => { | |
array.forEach(val => observer.next(val)); | |
observer.complete(); | |
}); | |
} | |
static fromEvent(element, event) { | |
return new Observable(observer => { | |
const handler = (e) => observer.next(e); | |
element.addEventListener(event, handler); | |
return () => { | |
element.removeEventListener(event, handler); | |
}; | |
}); | |
} | |
static fromPromise(promise) { | |
return new Observable(observer => { | |
promise.then(val => { | |
observer.next(val); observer.complete(); | |
}) | |
.catch(e => { | |
observer.error(val); observer.complete(); | |
}); | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line's 11 and 12 throw "Unexpected token" errors for me. I think if you wrap the fat arrow functions with paren's it should be fine:
error: error || (() => {}),
complete: complete || (() => {})