UNPKG

2.46 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.withCancel = exports.getAsyncIterableWithCancel = exports.getAsyncIteratorWithCancel = void 0;
4const memoize_js_1 = require("./memoize.js");
5async function defaultAsyncIteratorReturn(value) {
6 return { value, done: true };
7}
8const proxyMethodFactory = (0, memoize_js_1.memoize2)(function proxyMethodFactory(target, targetMethod) {
9 return function proxyMethod(...args) {
10 return Reflect.apply(targetMethod, target, args);
11 };
12});
13function getAsyncIteratorWithCancel(asyncIterator, onCancel) {
14 return new Proxy(asyncIterator, {
15 has(asyncIterator, prop) {
16 if (prop === 'return') {
17 return true;
18 }
19 return Reflect.has(asyncIterator, prop);
20 },
21 get(asyncIterator, prop, receiver) {
22 const existingPropValue = Reflect.get(asyncIterator, prop, receiver);
23 if (prop === 'return') {
24 const existingReturn = existingPropValue || defaultAsyncIteratorReturn;
25 return async function returnWithCancel(value) {
26 const returnValue = await onCancel(value);
27 return Reflect.apply(existingReturn, asyncIterator, [returnValue]);
28 };
29 }
30 else if (typeof existingPropValue === 'function') {
31 return proxyMethodFactory(asyncIterator, existingPropValue);
32 }
33 return existingPropValue;
34 },
35 });
36}
37exports.getAsyncIteratorWithCancel = getAsyncIteratorWithCancel;
38function getAsyncIterableWithCancel(asyncIterable, onCancel) {
39 return new Proxy(asyncIterable, {
40 get(asyncIterable, prop, receiver) {
41 const existingPropValue = Reflect.get(asyncIterable, prop, receiver);
42 if (Symbol.asyncIterator === prop) {
43 return function asyncIteratorFactory() {
44 const asyncIterator = Reflect.apply(existingPropValue, asyncIterable, []);
45 return getAsyncIteratorWithCancel(asyncIterator, onCancel);
46 };
47 }
48 else if (typeof existingPropValue === 'function') {
49 return proxyMethodFactory(asyncIterable, existingPropValue);
50 }
51 return existingPropValue;
52 },
53 });
54}
55exports.getAsyncIterableWithCancel = getAsyncIterableWithCancel;
56exports.withCancel = getAsyncIterableWithCancel;