Skip to content

Instantly share code, notes, and snippets.

@calebmer
Last active February 27, 2020 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calebmer/73644e04b2148f45c93315c082091cc0 to your computer and use it in GitHub Desktop.
Save calebmer/73644e04b2148f45c93315c082091cc0 to your computer and use it in GitHub Desktop.
Caleb’s Collection of utilities
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);
}
}
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,
};
import queueUncaughtException from './queueUncaughtException';
const microtaskPromise = Promise.resolve();
export default function queueMicrotask(callback: () => void) {
microtaskPromise.then(callback).catch(queueUncaughtException);
}
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