import type { AnyParams } from "../../../types/array"; import type { Creater, Func, Method } from "../../../types/concepts"; import type { DeepPartial } from "../../../types/object"; import { die } from "../../../utils/internal/exceptions"; import { noop } from "../../../utils/typed-function"; import type { CacheMap } from "../data-structure/interfaces/schema"; import { argument } from "../functions/argument"; type ProtectedRecursiveParam = [param: T]; type ProtectedRecursiveCaller = Func< ProtectedRecursiveParam, ProtectedRecursiveCallRequest >; export type RecursiveCallGenerator = Generator; export type ProtectedRecursiveCallGenerator = RecursiveCallGenerator< ProtectedRecursiveCallRequest, R >; export type RawRecursiveCallGenerator< P extends AnyParams, R > = RecursiveCallGenerator; interface ProtectedRecursiveCallMemoConfig { /** * Whether to use cache by parameter. * default `false` */ cacheParam: boolean; /** * The cache factory function. * default `() => new Map()` */ cacheFactory: Creater>; } interface RecursiveConfig { /** * Max recursive stack size. `Infinity` by default. */ maxStack: number; } export interface RecursiveCallConfig extends RecursiveConfig { memo: ProtectedRecursiveCallMemoConfig; } interface ProtectedRecursiveCallRequest { readonly payload: T; } interface RawRecursiveCallThisContext

{ call: Func; /** * The internal iterator stack. * Don't try to invoke `generator.next()` or modify it, or the stack might be corrupted. */ stack: RawRecursiveCallGenerator[]; } interface ProtectedRecursiveCallThisContext { call: ProtectedRecursiveCaller; } interface GeneralRecursiveCallThisContext

{ // Not type safe. // eslint-disable-next-line @typescript-eslint/no-explicit-any call: Func; } export type RawRecursiveCallFactory

= Method< RawRecursiveCallThisContext, P, RawRecursiveCallGenerator >; export type ProtectedRecursiveCallFactory = Method< ProtectedRecursiveCallThisContext, ProtectedRecursiveParam, ProtectedRecursiveCallGenerator >; /** * To make factory functions with only one parameter to work with both {@link protectedRecursive} and {@link rawRecursive}, use this type for annotation. * It's not completely type safe, so make sure to use `yield this.call(param)` to perform a recursive call. */ export type GeneralRecursiveFactory = Method< GeneralRecursiveCallThisContext>, ProtectedRecursiveParam, // Not type safe. // eslint-disable-next-line @typescript-eslint/no-explicit-any Generator >; /** * Perform a recursive computation without increasing call stack frames as the recursion grow. * A Fibonacci sequence example with this API: * ```ts * // 1. Define a recursive function by call this API like this: * const fibo = rawRecursive<[n: number], number>( * // 2. Pass a generator function as the parameter * function* (n) { * if (n === 0 || n === 1) { * return 1; * } * // 3. Use `yield this.call(...params)` to perform a recursive call * const fn2 = yield this.call(n - 2); * const fn1 = yield this.call(n - 1); * return fn2 + fn1; * }); * // 4. Use the defined recursive function to compute: * console.log(fibo(1)) // 1 * console.log(fibo(2)) // 2 * console.log(fibo(8)) // 34 * ``` * @param factory the factory function which returns a generator * @returns sync recursive result */ export const rawRecursive =

( factory: RawRecursiveCallFactory ): Func => { return (...args) => { const stack: RawRecursiveCallGenerator[] = []; const ctx: RawRecursiveCallThisContext = { call: argument, stack, }; const invoke = (args: P) => { const iterator = factory.apply(ctx, args); const initIteration = iterator.next(); stack.push(iterator); return [iterator, initIteration] as const; }; let [iterator, iteration] = invoke(args); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { if (iteration.done) { stack.pop(); const nextIterator = stack.at(-1); if (!nextIterator) { break; } iterator = nextIterator; iteration = iterator.next(iteration.value); } else { [iterator, iteration] = invoke(iteration.value); } } return iteration.value; }; }; const stackOverflow = () => die("Stack overflow."); const circlularFrame = () => die( "Cannot yield `this.call` result more than once when the last `yield` is not done, which may lead to infinite loop." ); const uncheckedCall = (...codes: string[]) => die( `Unknown stack frame. Invoke the passed ${codes .map((code) => `\`${code}\``) .join(" ")} function to create stack frame.` ); /** * Same core logic with {@link rawRecursive} but safer than {@link rawRecursive} with extra config. * This API calls {@link rawRecursive} internally. * The parameter generator function should have **exactly one parameter**. * A Fibonacci sequence example with this API: * ```ts * // 1. Define a recursive function by call this API like this: * const fibo = protectedRecursive( * // 2. Pass a generator function as the parameter. * function* (n) { * if (n === 0 || n === 1) { * return 1; * } * // 3. Use `yield this.call(params)` to perform a recursive call * const fn2 = yield this.call(n - 2); * const fn1 = yield this.call(n - 1); * return fn2 + fn1; * }); * // 4. Use the defined recursive function to compute: * console.log(fibo(1)) // 1 * console.log(fibo(2)) // 2 * console.log(fibo(8)) // 34 * ``` * @param factory the factory function which returns a generator * @param config the config * @returns sync recursive result */ export const protectedRecursive = ( factory: ProtectedRecursiveCallFactory, config?: DeepPartial> ) => { type StackState = "init" | "started"; const maxStack = config?.maxStack ?? Infinity; const cacheParam = config?.memo?.cacheParam ?? false; const cache = cacheParam ? (config?.memo?.cacheFactory ?? (() => new Map()))() : (null as never); const memorizeIfNeedCache = cacheParam ? (param: T, result: R) => { if (!cache.has(param)) { cache.set(param, result); } } : noop; type P = ProtectedRecursiveParam; const createResult = (value: R) => (function* () { return value; })(); const requestState = new WeakMap< ProtectedRecursiveCallRequest, StackState | { result: R } >(); return rawRecursive(function (value) { if (cacheParam && cache.has(value)) { return createResult(cache.get(value)!); } const ctx: ProtectedRecursiveCallThisContext = { call: (payload) => { const request: ProtectedRecursiveCallRequest = Object.freeze({ payload, }); requestState.set(request, "init"); return request; }, }; return function* ( this: RawRecursiveCallThisContext, passedValue: T ): RawRecursiveCallGenerator { if (this.stack.length >= maxStack) { return stackOverflow(); } const generator = factory.call(ctx, passedValue); let iteration = generator.next(); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { if (!iteration.done) { const request = iteration.value; const state = requestState.get(request); if (state === undefined) { return uncheckedCall("this.call"); } else if (state === "init") { requestState.set(request, "started"); const param = request.payload; const result = yield this.call(param); requestState.set(request, { result }); iteration = generator.next(result); } else if (state === "started") { return circlularFrame(); } else { iteration = generator.next(state.result); } } else { const result = iteration.value; memorizeIfNeedCache(passedValue, result); return result; } } }.call(this, value); }); }; export const recursive = protectedRecursive; interface RecursiveGeneratorValueRequest { readonly type: "value"; readonly payload: T; } interface RecursiveGeneratorSequenceRequest

{ readonly type: "seq"; readonly payload: P; } type RecursiveGeneratorRequest

= | RecursiveGeneratorSequenceRequest

| RecursiveGeneratorValueRequest; interface RecursiveGeneratorValueResponse { type: "next"; payload: N; } interface RecursiveGeneratorSequenceResponse { type: "return"; payload: R; } type RecursiveGeneratorResponse = | RecursiveGeneratorSequenceResponse | RecursiveGeneratorValueResponse; interface RawRecursiveGeneratorThisContext< P extends AnyParams, T, R = void, N = void > extends ProtectedRecursiveGeneratorThisContext { stack: RecursiveGenerator[]; } interface ProtectedRecursiveGeneratorThisContext

{ value: Func<[value: T], RecursiveGeneratorValueRequest>; sequence: Func>; } type RecursiveGenerator

= Generator< RecursiveGeneratorRequest, R, RecursiveGeneratorResponse >; export type RawRecursiveGeneratorFactory< P extends AnyParams, T, R = void, N = void > = Method< RawRecursiveGeneratorThisContext, P, RecursiveGenerator >; export type ProtectedRecursiveGeneratorFactory< P extends AnyParams, T, R = void, N = void > = Method< ProtectedRecursiveGeneratorThisContext, P, RecursiveGenerator >; export const rawRecursiveGenerator = < P extends AnyParams, T, R = void, N = void >( factory: RawRecursiveGeneratorFactory ) => { type G = RecursiveGenerator; return function* (...args: P): Generator { const stack: G[] = []; const ctx: RawRecursiveGeneratorThisContext = { value: (value) => ({ type: "value", payload: value, }), sequence: (...args) => ({ type: "seq", payload: args, }), stack, }; const invoke = (args: P) => { const iterator = factory.apply(ctx, args); const initIteration = iterator.next(); stack.push(iterator); return [iterator, initIteration] as const; }; let [iterator, iteration] = invoke(args); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { if (iteration.done) { stack.pop(); const nextIterator = stack.at(-1); if (!nextIterator) { break; } iterator = nextIterator; iteration = iterator.next({ type: "return", payload: iteration.value }); } else { const request = iteration.value; if (request.type === "seq") { [iterator, iteration] = invoke(request.payload); } else { const next = yield request.payload; iteration = iterator.next({ type: "next", payload: next }); } } } return iteration.value; }; }; export const protectedRecursiveGenerator = < P extends AnyParams, T, R = void, N = void >( factory: ProtectedRecursiveGeneratorFactory, config?: Partial ) => { const maxStack = config?.maxStack ?? Infinity; return rawRecursiveGenerator(function (...args: P) { const trackedRequests = new WeakSet>(); const ctx: ProtectedRecursiveGeneratorThisContext = { value: (value) => { const result = this.value(value); trackedRequests.add(result); Object.freeze(result); return result; }, sequence: (...args: P) => { const result = this.sequence(...args); trackedRequests.add(result); Object.freeze(result); return result; }, }; return function* ( this: RawRecursiveGeneratorThisContext, ...passedArgs: P ): RecursiveGenerator { if (this.stack.length >= maxStack) { return stackOverflow(); } const generator = factory.apply(ctx, passedArgs); let iteration = generator.next(); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { if (!iteration.done) { const request = iteration.value; if (!trackedRequests.has(request)) { return uncheckedCall("this.value", "this.sequence"); } iteration = generator.next(yield request); } else { return iteration.value; } } }.apply(this, args); }); }; export const recursiveGenerator = protectedRecursiveGenerator;