{
  "version": 3,
  "sources": ["../../../../src/libs/custom/algorithms/recursive.mts"],
  "sourcesContent": ["import type { AnyParams } from \"../../../types/array.mjs\";\nimport type { Creater, Func, Method } from \"../../../types/concepts.mjs\";\nimport type { DeepPartial } from \"../../../types/object.mjs\";\nimport { die } from \"../../../utils/internal/exceptions.mjs\";\nimport { noop } from \"../../../utils/typed-function.mjs\";\nimport type { CacheMap } from \"../data-structure/interfaces/schema.mjs\";\nimport { argument } from \"../functions/argument.mjs\";\n\ntype ProtectedRecursiveParam<T> = [param: T];\ntype ProtectedRecursiveCaller<T> = Func<\n  ProtectedRecursiveParam<T>,\n  ProtectedRecursiveCallRequest<T>\n>;\n\nexport type RecursiveCallGenerator<T, R> = Generator<T, R, R>;\n\nexport type ProtectedRecursiveCallGenerator<T, R> = RecursiveCallGenerator<\n  ProtectedRecursiveCallRequest<T>,\n  R\n>;\n\nexport type RawRecursiveCallGenerator<\n  P extends AnyParams,\n  R\n> = RecursiveCallGenerator<P, R>;\n\ninterface ProtectedRecursiveCallMemoConfig<T, R> {\n  /**\n   * Whether to use cache by parameter.\n   * default `false`\n   */\n  cacheParam: boolean;\n  /**\n   * The cache factory function.\n   * default `() => new Map<T, R>()`\n   */\n  cacheFactory: Creater<CacheMap<T, R>>;\n}\n\ninterface RecursiveConfig {\n  /**\n   * Max recursive stack size. `Infinity` by default.\n   */\n  maxStack: number;\n}\n\nexport interface RecursiveCallConfig<T, R> extends RecursiveConfig {\n  memo: ProtectedRecursiveCallMemoConfig<T, R>;\n}\n\ninterface ProtectedRecursiveCallRequest<T> {\n  readonly payload: T;\n}\n\ninterface RawRecursiveCallThisContext<P extends AnyParams, R> {\n  call: Func<P, P>;\n  /**\n   * The internal iterator stack.\n   * Don't try to invoke `generator.next()` or modify it, or the stack might be corrupted.\n   */\n  stack: RawRecursiveCallGenerator<P, R>[];\n}\ninterface ProtectedRecursiveCallThisContext<T> {\n  call: ProtectedRecursiveCaller<T>;\n}\n\ninterface GeneralRecursiveCallThisContext<P extends AnyParams> {\n  // Not type safe.\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  call: Func<P, any>;\n}\n\nexport type RawRecursiveCallFactory<P extends AnyParams, R> = Method<\n  RawRecursiveCallThisContext<P, R>,\n  P,\n  RawRecursiveCallGenerator<P, R>\n>;\n\nexport type ProtectedRecursiveCallFactory<T, R> = Method<\n  ProtectedRecursiveCallThisContext<T>,\n  ProtectedRecursiveParam<T>,\n  ProtectedRecursiveCallGenerator<T, R>\n>;\n\n/**\n * To make factory functions with only one parameter to work with both {@link protectedRecursive} and {@link rawRecursive}, use this type for annotation.\n * It's not completely type safe, so make sure to use `yield this.call(param)` to perform a recursive call.\n */\nexport type GeneralRecursiveFactory<T, R> = Method<\n  GeneralRecursiveCallThisContext<ProtectedRecursiveParam<T>>,\n  ProtectedRecursiveParam<T>,\n  // Not type safe.\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  Generator<any, R, R>\n>;\n\n/**\n * Perform a recursive computation without increasing call stack frames as the recursion grow.\n * A Fibonacci sequence example with this API:\n * ```ts\n * // 1. Define a recursive function by call this API like this:\n * const fibo = rawRecursive<[n: number], number>(\n * // 2. Pass a generator function as the parameter\n * function* (n) {\n *   if (n === 0 || n === 1) {\n *     return 1;\n *   }\n *   // 3. Use `yield this.call(...params)` to perform a recursive call\n *   const fn2 = yield this.call(n - 2);\n *   const fn1 = yield this.call(n - 1);\n *   return fn2 + fn1;\n * });\n * // 4. Use the defined recursive function to compute:\n * console.log(fibo(1)) // 1\n * console.log(fibo(2)) // 2\n * console.log(fibo(8)) // 34\n * ```\n * @param factory the factory function which returns a generator\n * @returns sync recursive result\n */\nexport const rawRecursive = <P extends AnyParams, R>(\n  factory: RawRecursiveCallFactory<P, R>\n): Func<P, R> => {\n  return (...args) => {\n    const stack: RawRecursiveCallGenerator<P, R>[] = [];\n    const ctx: RawRecursiveCallThisContext<P, R> = {\n      call: argument,\n      stack,\n    };\n    const invoke = (args: P) => {\n      const iterator = factory.apply(ctx, args);\n      const initIteration = iterator.next();\n      stack.push(iterator);\n      return [iterator, initIteration] as const;\n    };\n    let [iterator, iteration] = invoke(args);\n    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n    while (true) {\n      if (iteration.done) {\n        stack.pop();\n        const nextIterator = stack.at(-1);\n        if (!nextIterator) {\n          break;\n        }\n        iterator = nextIterator;\n        iteration = iterator.next(iteration.value);\n      } else {\n        [iterator, iteration] = invoke(iteration.value);\n      }\n    }\n    return iteration.value;\n  };\n};\nconst stackOverflow = () => die(\"Stack overflow.\");\nconst circlularFrame = () =>\n  die(\n    \"Cannot yield `this.call` result more than once when the last `yield` is not done, which may lead to infinite loop.\"\n  );\n\nconst uncheckedCall = (...codes: string[]) =>\n  die(\n    `Unknown stack frame. Invoke the passed ${codes\n      .map((code) => `\\`${code}\\``)\n      .join(\" \")} function to create stack frame.`\n  );\n\n/**\n * Same core logic with {@link rawRecursive} but safer than {@link rawRecursive} with extra config.\n * This API calls {@link rawRecursive} internally.\n * The parameter generator function should have **exactly one parameter**.\n * A Fibonacci sequence example with this API:\n * ```ts\n * // 1. Define a recursive function by call this API like this:\n * const fibo = protectedRecursive<number, number>(\n * // 2. Pass a generator function as the parameter.\n * function* (n) {\n *   if (n === 0 || n === 1) {\n *     return 1;\n *   }\n *   // 3. Use `yield this.call(params)` to perform a recursive call\n *   const fn2 = yield this.call(n - 2);\n *   const fn1 = yield this.call(n - 1);\n *   return fn2 + fn1;\n * });\n * // 4. Use the defined recursive function to compute:\n * console.log(fibo(1)) // 1\n * console.log(fibo(2)) // 2\n * console.log(fibo(8)) // 34\n * ```\n * @param factory the factory function which returns a generator\n * @param config the config\n * @returns sync recursive result\n */\nexport const protectedRecursive = <T, R>(\n  factory: ProtectedRecursiveCallFactory<T, R>,\n  config?: DeepPartial<RecursiveCallConfig<T, R>>\n) => {\n  type StackState = \"init\" | \"started\";\n  const maxStack = config?.maxStack ?? Infinity;\n  const cacheParam = config?.memo?.cacheParam ?? false;\n  const cache = cacheParam\n    ? (config?.memo?.cacheFactory ?? (() => new Map<T, R>()))()\n    : (null as never);\n  const memorizeIfNeedCache = cacheParam\n    ? (param: T, result: R) => {\n        if (!cache.has(param)) {\n          cache.set(param, result);\n        }\n      }\n    : noop;\n  type P = ProtectedRecursiveParam<T>;\n  const createResult = (value: R) =>\n    (function* () {\n      return value;\n    })();\n  const requestState = new WeakMap<\n    ProtectedRecursiveCallRequest<T>,\n    StackState | { result: R }\n  >();\n  return rawRecursive<P, R>(function (value) {\n    if (cacheParam && cache.has(value)) {\n      return createResult(cache.get(value)!);\n    }\n    const ctx: ProtectedRecursiveCallThisContext<T> = {\n      call: (payload) => {\n        const request: ProtectedRecursiveCallRequest<T> = Object.freeze({\n          payload,\n        });\n        requestState.set(request, \"init\");\n        return request;\n      },\n    };\n    return function* (\n      this: RawRecursiveCallThisContext<P, R>,\n      passedValue: T\n    ): RawRecursiveCallGenerator<P, R> {\n      if (this.stack.length >= maxStack) {\n        return stackOverflow();\n      }\n      const generator = factory.call(ctx, passedValue);\n      let iteration = generator.next();\n      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n      while (true) {\n        if (!iteration.done) {\n          const request = iteration.value;\n          const state = requestState.get(request);\n          if (state === undefined) {\n            return uncheckedCall(\"this.call\");\n          } else if (state === \"init\") {\n            requestState.set(request, \"started\");\n            const param = request.payload;\n            const result = yield this.call(param);\n            requestState.set(request, { result });\n            iteration = generator.next(result);\n          } else if (state === \"started\") {\n            return circlularFrame();\n          } else {\n            iteration = generator.next(state.result);\n          }\n        } else {\n          const result = iteration.value;\n          memorizeIfNeedCache(passedValue, result);\n          return result;\n        }\n      }\n    }.call(this, value);\n  });\n};\nexport const recursive = protectedRecursive;\n\ninterface RecursiveGeneratorValueRequest<T> {\n  readonly type: \"value\";\n  readonly payload: T;\n}\n\ninterface RecursiveGeneratorSequenceRequest<P extends AnyParams> {\n  readonly type: \"seq\";\n  readonly payload: P;\n}\n\ntype RecursiveGeneratorRequest<P extends AnyParams, T> =\n  | RecursiveGeneratorSequenceRequest<P>\n  | RecursiveGeneratorValueRequest<T>;\n\ninterface RecursiveGeneratorValueResponse<N> {\n  type: \"next\";\n  payload: N;\n}\n\ninterface RecursiveGeneratorSequenceResponse<R> {\n  type: \"return\";\n  payload: R;\n}\n\ntype RecursiveGeneratorResponse<R, N> =\n  | RecursiveGeneratorSequenceResponse<R>\n  | RecursiveGeneratorValueResponse<N>;\n\ninterface RawRecursiveGeneratorThisContext<\n  P extends AnyParams,\n  T,\n  R = void,\n  N = void\n> extends ProtectedRecursiveGeneratorThisContext<P, T> {\n  stack: RecursiveGenerator<P, T, R, N>[];\n}\n\ninterface ProtectedRecursiveGeneratorThisContext<P extends AnyParams, T> {\n  value: Func<[value: T], RecursiveGeneratorValueRequest<T>>;\n  sequence: Func<P, RecursiveGeneratorSequenceRequest<P>>;\n}\n\ntype RecursiveGenerator<P extends AnyParams, T, R = void, N = void> = Generator<\n  RecursiveGeneratorRequest<P, T>,\n  R,\n  RecursiveGeneratorResponse<R, N>\n>;\n\nexport type RawRecursiveGeneratorFactory<\n  P extends AnyParams,\n  T,\n  R = void,\n  N = void\n> = Method<\n  RawRecursiveGeneratorThisContext<P, T, R, N>,\n  P,\n  RecursiveGenerator<P, T, R, N>\n>;\n\nexport type ProtectedRecursiveGeneratorFactory<\n  P extends AnyParams,\n  T,\n  R = void,\n  N = void\n> = Method<\n  ProtectedRecursiveGeneratorThisContext<P, T>,\n  P,\n  RecursiveGenerator<P, T, R, N>\n>;\n\nexport const rawRecursiveGenerator = <\n  P extends AnyParams,\n  T,\n  R = void,\n  N = void\n>(\n  factory: RawRecursiveGeneratorFactory<P, T, R, N>\n) => {\n  type G = RecursiveGenerator<P, T, R, N>;\n  return function* (...args: P): Generator<T, R, N> {\n    const stack: G[] = [];\n    const ctx: RawRecursiveGeneratorThisContext<P, T, R, N> = {\n      value: (value) => ({\n        type: \"value\",\n        payload: value,\n      }),\n      sequence: (...args) => ({\n        type: \"seq\",\n        payload: args,\n      }),\n      stack,\n    };\n    const invoke = (args: P) => {\n      const iterator = factory.apply(ctx, args);\n      const initIteration = iterator.next();\n      stack.push(iterator);\n      return [iterator, initIteration] as const;\n    };\n    let [iterator, iteration] = invoke(args);\n    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n    while (true) {\n      if (iteration.done) {\n        stack.pop();\n        const nextIterator = stack.at(-1);\n        if (!nextIterator) {\n          break;\n        }\n        iterator = nextIterator;\n        iteration = iterator.next({ type: \"return\", payload: iteration.value });\n      } else {\n        const request = iteration.value;\n        if (request.type === \"seq\") {\n          [iterator, iteration] = invoke(request.payload);\n        } else {\n          const next = yield request.payload;\n          iteration = iterator.next({ type: \"next\", payload: next });\n        }\n      }\n    }\n    return iteration.value;\n  };\n};\n\nexport const protectedRecursiveGenerator = <\n  P extends AnyParams,\n  T,\n  R = void,\n  N = void\n>(\n  factory: ProtectedRecursiveGeneratorFactory<P, T, R, N>,\n  config?: Partial<RecursiveConfig>\n) => {\n  const maxStack = config?.maxStack ?? Infinity;\n\n  return rawRecursiveGenerator<P, T, R, N>(function (...args: P) {\n    const trackedRequests = new WeakSet<RecursiveGeneratorRequest<P, T>>();\n    const ctx: ProtectedRecursiveGeneratorThisContext<P, T> = {\n      value: (value) => {\n        const result = this.value(value);\n        trackedRequests.add(result);\n        Object.freeze(result);\n        return result;\n      },\n      sequence: (...args: P) => {\n        const result = this.sequence(...args);\n        trackedRequests.add(result);\n        Object.freeze(result);\n        return result;\n      },\n    };\n    return function* (\n      this: RawRecursiveGeneratorThisContext<P, T, R, N>,\n      ...passedArgs: P\n    ): RecursiveGenerator<P, T, R, N> {\n      if (this.stack.length >= maxStack) {\n        return stackOverflow();\n      }\n      const generator = factory.apply(ctx, passedArgs);\n      let iteration = generator.next();\n      // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n      while (true) {\n        if (!iteration.done) {\n          const request = iteration.value;\n          if (!trackedRequests.has(request)) {\n            return uncheckedCall(\"this.value\", \"this.sequence\");\n          }\n          iteration = generator.next(yield request);\n        } else {\n          return iteration.value;\n        }\n      }\n    }.apply(this, args);\n  });\n};\n\nexport const recursiveGenerator = protectedRecursiveGenerator;\n"],
  "mappings": "AAGA;AACA;AAEA;AAkHO,MAAM,eAAe,CAC1B,YACe;AACf,SAAO,IAAI,SAAS;AAClB,UAAM,QAA2C;AACjD,UAAM,MAAyC;AAAA,MAC7C,MAAM;AAAA,MACN;AAAA;AAEF,UAAM,SAAS,CAAC,UAAY;AAC1B,YAAM,YAAW,QAAQ,MAAM,KAAK;AACpC,YAAM,gBAAgB,UAAS;AAC/B,YAAM,KAAK;AACX,aAAO,CAAC,WAAU;AAAA;AAEpB,QAAI,CAAC,UAAU,aAAa,OAAO;AAEnC,WAAO,MAAM;AACX,UAAI,UAAU,MAAM;AAClB,cAAM;AACN,cAAM,eAAe,MAAM,GAAG;AAC9B,YAAI,CAAC,cAAc;AACjB;AAAA;AAEF,mBAAW;AACX,oBAAY,SAAS,KAAK,UAAU;AAAA,aAC/B;AACL,SAAC,UAAU,aAAa,OAAO,UAAU;AAAA;AAAA;AAG7C,WAAO,UAAU;AAAA;AAAA;AAGrB,MAAM,gBAAgB,MAAM,IAAI;AAChC,MAAM,iBAAiB,MACrB,IACE;AAGJ,MAAM,gBAAgB,IAAI,UACxB,IACE,0CAA0C,MACvC,IAAI,CAAC,SAAS,KAAK,UACnB,KAAK;AA8BL,MAAM,qBAAqB,CAChC,SACA,WACG;AAEH,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,aAAa,QAAQ,MAAM,cAAc;AAC/C,QAAM,QAAQ,aACT,SAAQ,MAAM,gBAAiB,OAAM,oBAAI,YACzC;AACL,QAAM,sBAAsB,aACxB,CAAC,OAAU,WAAc;AACvB,QAAI,CAAC,MAAM,IAAI,QAAQ;AACrB,YAAM,IAAI,OAAO;AAAA;AAAA,MAGrB;AAEJ,QAAM,eAAe,CAAC,UACnB,aAAa;AACZ,WAAO;AAAA;AAEX,QAAM,eA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