Last active
July 16, 2018 20:54
-
-
Save alecmerdler/ecfd9ce02e87f062cd5859319c66ad0e to your computer and use it in GitHub Desktop.
Functional Web Worker 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
/** | |
* Service worker utilities. | |
* Inspired by https://github.com/deebloo/worker. | |
*/ | |
export type $worker = (fn: (event: MessageEvent) => void) => Worker; | |
export const $worker: $worker = fn => { | |
const blob: Blob = new Blob(['self.onmessage=', fn.toString(), ';'], {type: 'text/javascript'}); | |
const url: string = URL.createObjectURL(blob); | |
const worker: Worker = new Worker(url); | |
URL.revokeObjectURL(url); | |
return worker; | |
}; | |
export type $run = (worker: Worker) => (data?: any) => Promise<MessageEvent>; | |
export const $run: $run = worker => data => { | |
worker.postMessage(data); | |
return new Promise((resolve, reject) => { | |
worker.onmessage = resolve; | |
worker.onerror = reject; | |
}); | |
}; |
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
describe('$run', () => { | |
}); | |
describe('$worker', () => { | |
it('returns a Worker', () => { | |
const worker = $worker((e) => { | |
}); | |
expect(worker instanceof Worker).toBe(true); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment