import type { AnyArray, CutFirst, EmptyTuple, TupleSlices, } from "../../../types/array"; import type { AnyFunc, Func } from "../../../types/concepts"; import type { Placeholder } from "./placeholder"; import { isPlaceholder, _$_ } from "./placeholder"; type PlaceHoldedParams
= P extends EmptyTuple
? []
: [P[0] | Placeholder, ...PlaceHoldedParams extends EmptyTuple ? R : Currying
? ApplyArgs , ...ApplyArgs = <
Args extends TupleSlices ;
const internalCurrying =
(fn: AnyFunc, passed: unknown[]) =>
(...args: unknown[]) => {
const newPassed = passed.slice();
const toFill: number[] = [];
for (let i = 0; i < passed.length; i++) {
if (isPlaceholder(passed[i])) {
toFill.push(i);
}
}
for (let i = 0; i < args.length; i++) {
const index = toFill[i];
if (index === undefined) {
break;
}
newPassed[index] = args[i];
}
if (newPassed.every((param) => !isPlaceholder(param))) {
return fn(...newPassed);
} else {
return internalCurrying(fn, newPassed);
}
};
export const currying = (
fn: Func ,
count?: P["length"]
): Currying => {
count = count ?? fn.length;
const passed: unknown[] = new Array(count).fill(_$_);
// @ts-expect-error Implementation detail
return internalCurrying(fn, passed);
};