Last active
February 27, 2020 21:21
-
-
Save calebmer/73644e04b2148f45c93315c082091cc0 to your computer and use it in GitHub Desktop.
Caleb’s Collection of utilities
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
import queueUncaughtException from './queueUncaughtException'; | |
export default class Emitter<T> { | |
private readonly _listeners = new Set<(data: T) => void>(); | |
emit(data: T) { | |
this._listeners.forEach(callback => { | |
try { | |
callback(data); | |
} catch (error) { | |
queueUncaughtException(error); | |
} | |
}); | |
} | |
addListener(listener: (data: T) => void) { | |
this._listeners.add(listener); | |
} | |
removeListener(listener: (data: T) => void) { | |
this._listeners.delete(listener); | |
} | |
} |
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
export default class LazyMap<K, V> { | |
private readonly _get: (key: K) => V; | |
private readonly _map = new Map<K, Entry<V>>(); | |
constructor(get: (key: K) => V) { | |
this._get = get; | |
} | |
public get(key: K): V { | |
let entry = this._map.get(key); | |
if (entry === undefined) { | |
try { | |
const value = this._get(key); | |
entry = {completion: 'normal', value}; | |
} catch (value) { | |
entry = {completion: 'abrupt', value}; | |
} | |
this._map.set(key, entry); | |
} | |
if (entry.completion === 'normal') { | |
return entry.value; | |
} else { | |
throw entry.value; | |
} | |
} | |
} | |
type Entry<V> = { | |
completion: 'normal', | |
value: V, | |
} | { | |
completion: 'abrupt', | |
value: unknown, | |
}; |
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
import queueUncaughtException from './queueUncaughtException'; | |
const microtaskPromise = Promise.resolve(); | |
export default function queueMicrotask(callback: () => void) { | |
microtaskPromise.then(callback).catch(queueUncaughtException); | |
} |
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
export default function queueUncaughtException(error: unknown) { | |
setTimeout(() => { | |
throw error; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment