iter.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { AsyncLocalStorageProviderSingleton } from "../singletons/index.js";
  2. import { pickRunnableConfigKeys } from "./config.js";
  3. export function isIterableIterator(thing) {
  4. return (typeof thing === "object" &&
  5. thing !== null &&
  6. typeof thing[Symbol.iterator] === "function" &&
  7. // avoid detecting array/set as iterator
  8. typeof thing.next === "function");
  9. }
  10. export const isIterator = (x) => x != null &&
  11. typeof x === "object" &&
  12. "next" in x &&
  13. typeof x.next === "function";
  14. export function isAsyncIterable(thing) {
  15. return (typeof thing === "object" &&
  16. thing !== null &&
  17. typeof thing[Symbol.asyncIterator] ===
  18. "function");
  19. }
  20. export function* consumeIteratorInContext(context, iter) {
  21. while (true) {
  22. const { value, done } = AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iter.next.bind(iter), true);
  23. if (done) {
  24. break;
  25. }
  26. else {
  27. yield value;
  28. }
  29. }
  30. }
  31. export async function* consumeAsyncIterableInContext(context, iter) {
  32. const iterator = iter[Symbol.asyncIterator]();
  33. while (true) {
  34. const { value, done } = await AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(context), iterator.next.bind(iter), true);
  35. if (done) {
  36. break;
  37. }
  38. else {
  39. yield value;
  40. }
  41. }
  42. }