Created
February 15, 2017 22:58
-
-
Save anaisbetts/4d50d688cd866324ba8f01831627038e to your computer and use it in GitHub Desktop.
TypeScript Is Amazing
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
// | |
// WRONG | |
/// | |
class InMemorySparseMap<K, V> implements SparseMap<K, V> { | |
private latest: Map<K, Updatable<V>>; | |
private factory: ((key: K) => Observable<V>) | undefined; | |
subscribe(key: K): Updatable<V> { | |
let ret = this.latest.get(key); | |
if (ret) return ret; | |
if (this.factory) { | |
// *** TypeScript reports this.factory can be null!! WTF!!! *** | |
ret = new Updatable<V>(() => this.factory(key)); | |
} else { | |
ret = new Updatable<V>(); | |
} | |
this.latest.set(key, ret); | |
return ret; | |
} | |
} | |
// BUT | |
// The closure captures *this*, not *this.factory*. | |
// SO | |
// this.factory could be changed *later* to be undefined | |
// | |
// Right version! | |
// | |
if (this.factory) { | |
// Capture this.factory at the time of the call | |
const fact = this.factory.bind(this); | |
ret = new Updatable<V>(() => fact(key)); | |
} else { | |
ret = new Updatable<V>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment