Comparing version 0.0.9 to 0.0.10
@@ -10,1 +10,12 @@ export interface IDefer<T> { | ||
export default function makeDefer<T = void>(): IDefer<T>; | ||
export declare function makeBroadcastStream<T>(): { | ||
[x: number]: () => AsyncIterator<T>; | ||
listen(onNext: (value: T) => any, {onError, onDone}?: { | ||
onError?(error: unknown): any; | ||
onDone?(): any; | ||
}): (this: void) => void; | ||
next(value: T): void; | ||
throw(error: unknown): void; | ||
done(): void; | ||
}; |
53
index.js
@@ -16,1 +16,54 @@ 'use strict' | ||
} | ||
module.exports.makeBroadcastStream = function makeBroadcastStream() { | ||
const listeners = [] | ||
let done = false | ||
let defer = makeDefer() | ||
return { | ||
[Symbol.asyncIterator]() { | ||
return { | ||
next() { | ||
return defer.promise | ||
}, | ||
return() { | ||
}, | ||
throw() { | ||
} | ||
} | ||
}, | ||
listen(onNext, {onError, onDone} = {}) { | ||
if (done) | ||
throw new Error('Cannot listen after done') | ||
const listener = {onNext, onError, onDone} | ||
listeners.push(listener) | ||
return function removeListener() { | ||
const idx = listeners.lastIndexOf(listener) | ||
if (idx >= 0) | ||
listeners.splice(idx, 1) | ||
} | ||
}, | ||
next(value) { | ||
if (done) | ||
throw new Error('Cannot next after done') | ||
defer.resolve({value, done: false}) | ||
for (const {onNext} of listeners) | ||
onNext(value) | ||
}, | ||
throw(error) { | ||
if (done) | ||
throw new Error('Cannot throw after done') | ||
done = true | ||
defer.reject(error) | ||
for (const {onError} of listeners) | ||
onError === null || onError === void 0 ? void 0 : onError(error) | ||
}, | ||
done() { | ||
if (done) | ||
throw new Error('Cannot done after done') | ||
done = true | ||
defer.resolve({done: true}) | ||
for (const {onDone} of listeners) | ||
onDone === null || onDone === void 0 ? void 0 : onDone() | ||
}, | ||
} | ||
} |
{ | ||
"name": "jdefer", | ||
"version": "0.0.9", | ||
"version": "0.0.10", | ||
"main": "index.js", | ||
@@ -23,4 +23,4 @@ "repository": "https://github.com/tranvansang/jdefer", | ||
], | ||
"author": "Tran Sang <t@sang.jp>", | ||
"author": "Sang Tran <t@sang.jp>", | ||
"license": "MIT" | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
4491
147