/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /* eslint-disable @typescript-eslint/no-explicit-any */ // use '../internal/base' instead of '../internal' to avoid ↓ // - ReferenceError: Cannot access '***' before initialization // - because some of internal modules import the "../functional" /** * 在 TypeScript 里实现通用的柯里化函数是一件比较困难的事情。 * * 以下是一些讨论: * * - [Generic curry function with TypeScript 3 - stack overflow](https://stackoverflow.com/questions/51859461/generic-curry-function-with-typescript-3) * - [TypeScript and currying - GitHub Gist](https://gist.github.com/donnut/fd56232da58d25ceecf1) * * 这是目前为止我找到的最好的一个解决方案,我大幅度借鉴了这个方案,感谢 Mills: * * - [How to master advanced TypeScript patterns - Pierre-Antoine Mills](https://www.freecodecamp.org/news/typescript-curry-ramda-types-f747e99744ab/) * - [Related Repo](https://github.com/pirix-gh/medium/blob/master/types-curry-ramda/src/index.ts) * * 这个也不错: * * - [Currying in TypeScript - Jamie Pennell](https://medium.com/codex/currying-in-typescript-ca5226c85b85) * * 这是相关的 PR、Proposal、Updates: * * - [[Ramda] Generic types for curry #33628](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/33628) * - [Proposal: Variadic Kinds -- Give specific types to variadic functions #5453](https://github.com/Microsoft/TypeScript/issues/5453) * - [Variadic tuple types #39094](https://github.com/microsoft/TypeScript/pull/39094) * - [Variadic Tuple Types - TypeScript 4.0](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#variadic-tuple-types) */ import { asIs, isObject, isFunction } from '../internal/base' // NOTE: 重复实现了 boolean 中的 complement 以避免循环引用 type FunctionReturnBoolean = (...args: any[]) => boolean const complement = (fn: FunctionReturnBoolean): FunctionReturnBoolean => (...args) => !fn(...args) interface ArgPlaceholder { '@@functional/placeholder': true isArgPlaceholder: true } export const argPlaceholder: ArgPlaceholder = { // be compatible with ramda '@@functional/placeholder': true, isArgPlaceholder: true } /** * 判断一个参数是否是 ArgPlaceHolder */ export const isArgPlaceholder = (tar: any): tar is ArgPlaceholder => isObject(tar) && (tar.isArgPlaceholder === true || tar['@@functional/placeholder'] === true) /****************************************************************************************************** * * Simple Curry Function * ******************************************************************************************************/ type Loose = [...T, ...any[]] type PartialTuple = // If the tuple provided has at least one required value TUPLE extends [infer NEXT_PARAM, ...infer REMAINING] ? // recurse back in to this type with one less item // in the original tuple, and the latest extracted value // added to the extracted list as optional PartialTuple : // else if there are no more values, // return an empty tuple so that too is a valid option [...EXTRACTED, ...TUPLE] type NonNull = { [K in keyof T]: NonNullable } type PartialParameters any> = NonNull>> type RemainingParameters = // if the expected array has any required items EXPECTED extends [infer E1, ...infer EX] ? ( // if the provided array has at least one required item PROVIDED extends [infer P1, ...infer PX] ? ( // if the type is correct, recurse with one item less in each array type, // else return this as invalid P1 extends E1 ? RemainingParameters : never ) // else the remaining args is unchanged : (LOOSE extends true ? Loose : EXPECTED) ) // else there are no more arguments : (LOOSE extends true ? Loose<[]> : []) type SimpleCurriedFunctionOrReturnValue< PROVIDED extends any[], FN extends (...args: any[]) => any, LOOSE extends boolean = false > = RemainingParameters, LOOSE> extends [any, ...any[]] ? SimpleCurriedFunction : ReturnType type SimpleCurriedFunction< PROVIDED extends any[], FN extends (...args: any[]) => any, LOOSE extends boolean = false > = , LOOSE>>>> (...args: APPENDING_ARGS) => SimpleCurriedFunctionOrReturnValue<[...PROVIDED, ...APPENDING_ARGS], FN, LOOSE> type LooseCurryS = any, EXISTING_ARGS extends [...PartialParameters, ...any[]]> (targetFn: FN, ...existingArgs: EXISTING_ARGS) => SimpleCurriedFunction type HPLooseCurryS = (fn: AnyFunction, ...args: any[]) => AnyFunction /** * Simple curry function - loose version * * Loose simple curry will pass all of the args it received to target function, * even if the arg's length is greater than target function's arity. */ export const looseCurryS: LooseCurryS = (fn, ...existingArgs) => { return (...appendingArgs) => { const totalArgs = [...existingArgs, ...appendingArgs] if (totalArgs.length < fn.length) { return looseCurryS(fn, ...totalArgs as PartialParameters) // as PartialParameters } return fn(...totalArgs) } } type CurryS = any, EXISTING_ARGS extends PartialParameters> (targetFn: FN, ...existingArgs: EXISTING_ARGS) => SimpleCurriedFunction type HPCurryS = (fn: AnyFunction, ...args: any[]) => AnyFunction /** * Simple curry function - strict version * * Strict simple curry will take exactly the required args that target function needs, * redundant args will be ignored. */ export const curryS: CurryS = (fn, ...existingArgs) => { return (...appendingArgs) => { const targetArity = fn.length const totalArgs = [...existingArgs, ...appendingArgs] if (totalArgs.length < targetArity) { return curryS(fn, ...totalArgs as PartialParameters) // as PartialParameters } else { return fn(...totalArgs.slice(0, targetArity)) } } } /****************************************************************************************************** * * Curry Function * ******************************************************************************************************/ type Head = T extends [any, ...any[]] ? T[0] : never type Tail = ((...t: T) => any) extends ((_: any, ...tail: infer TT) => any) ? TT : [] type HasTail = T extends ([] | [any]) ? false : true type Last = { 0: Last>, 1: Head}[ HasTail extends true ? 0 : 1 ] type Length = T['length'] type Prepend = [E, ...T] type Drop = { 0: Drop, Prepend> 1: T }[ Length extends N ? 1 : 0] type Cast = X extends Y ? X : Y type Pos = Length type Next = Prepend type Prev = Tail type Iterator = { 0: Iterator, Next> 1: From }[ Pos extends Index ? 1 : 0 ] type Minus = Iterator extends infer target ? Drop> : never type Reverse = { 0: Reverse], R>, Next> 1: R }[ Pos extends Length ? 1 : 0 ] type Concat = Reverse extends infer R ? Cast : never, T2> type Append = Concat type LoosePlaceholder = [] & { __TYPE__: 'LoosePlaceholder' } // type example_ = GapOf<[ArgPlaceholder, number, ArgPlaceholder], [string, number, boolean], [], []> // [string] // type example_ = GapOf<[ArgPlaceholder, number, ArgPlaceholder], [string, number, boolean], [], [any, any]> // [boolean] // type example_ = GapOf<[ArgPlaceholder, number, ArgPlaceholder], [string, number], [], [any, any], true> // [LoosePlaceholder] // type example_ = GapOf<[ArgPlaceholder, number, ArgPlaceholder], [string, number], [], [any, any], false> // [] type GapOf< T1 extends any[], T2 extends any[], TN extends any[], I extends any[], LOOSE extends boolean = false > = T1[Pos] extends ArgPlaceholder ? ( LOOSE extends true ? (T2[Pos] extends undefined ? [...TN, LoosePlaceholder] : [...TN, T2[Pos]]) : (T2[Pos] extends undefined ? TN : [...TN, T2[Pos]]) ) : TN type GapsOf< T1 extends any[], T2 extends any[], LOOSE extends boolean = false, TN extends any[] = [], I extends any[] = [] > = { 0: GapsOf, any[]>, Next> 1: Concat, T2> extends infer D ? Cast : never> }[ Pos extends Length ? 1 : 0 ] // 使用 T2 填 T1 的空位,返回填充后的结果 // 在严格模式中,T2 中多余的参数会被丢弃,在宽松模式中会被保留 type ConcatGaps< T1 extends any[], T2 extends any[], LOOSE extends boolean = false, TN extends any[] = [] > = { 0: ConcatGaps< Tail, T1[0] extends ArgPlaceholder ? (Length extends 0 ? [] : Tail) : T2, LOOSE, T1[0] extends ArgPlaceholder ? (Length extends 0 ? [...TN, T1[0]] : [...TN, T2[0]]) : [...TN, T1[0]] > 1: LOOSE extends true ? [...TN, ...T2] : TN }[ Length extends 0 ? 1 : 0 ] // 使被柯里化的函数参数可以接受 argPlaceholder type PartialGaps = { [K in keyof T]?: T[K] extends LoosePlaceholder ? any : (T[K] | ArgPlaceholder) } type CleanedGaps = { [K in keyof T]: NonNullable } type Gaps = CleanedGaps> // 柯里化函数的基础类型 type CurriedFunctionOrReturnValue< PROVIDED extends any[], FN extends (...args: any[]) => any, LOOSE extends boolean = false > = // 判断柯里化函数的返回值需要准确的必需参数列表,所以这里的 GapsOf 始终是严格模式 GapsOf, false> extends [any, ...any[]] ? CurriedFunction : ReturnType type CurriedFunction< PROVIDED extends any[], FN extends (...args: any[]) => any, LOOSE extends boolean = false > = , LOOSE> extends infer _ ? (LOOSE extends true ? Gaps>> : Gaps>) : never ) > // ConcatGaps 应该始终使用严格模式,以使后续追加的参数能够正确地被记录到 Provide 中 (...args: APPENDING_ARGS) => ConcatGaps extends infer ___ ? CurriedFunctionOrReturnValue, FN, LOOSE> : never type LooseCurry = any, EXISTING_ARGS extends Loose>, any[]>>> (fn: FN, ...existingArgs: EXISTING_ARGS) => CurriedFunction type HPLooseCurry = (fn: AnyFunction, ...args: any[]) => AnyFunction /** * Internal curry function - loose version * * Loose internal curry will pass all of the args it received to target function, * even if the arg's length is greater than target function's arity. */ export const looseCurry: HPLooseCurry = (fn, ...existingArgs) => { return (...appendingArgs) => { const totalArgs = existingArgs.map(arg => isArgPlaceholder(arg) ? (appendingArgs.length > 0 ? appendingArgs.shift() : arg) : arg ) totalArgs.push(...appendingArgs) const targetArity = fn.length const validArgs = totalArgs.slice(0, targetArity) const validLen = validArgs.filter(complement(isArgPlaceholder)).length if (validLen < targetArity) { return looseCurry(fn, ...totalArgs) // as (typeof existingArgs) } else { return fn(...totalArgs) } } } type Curry = any, EXISTING_ARGS extends Cast>, any[]>> (fn: FN, ...existingArgs: EXISTING_ARGS) => CurriedFunction type HPCurry = (fn: AnyFunction, ...args: any[]) => AnyFunction /** * Internal curry function - strict version * * Strict internal curry will take exactly the required args that target function needs, * redundant args will be ignored. */ export const curry: HPCurry = (fn, ...existingArgs) => { return (...appendingArgs) => { const totalArgs = existingArgs.map(arg => isArgPlaceholder(arg) ? (appendingArgs.length > 0 ? appendingArgs.shift() : arg) : arg ) totalArgs.push(...appendingArgs) const targetArity = fn.length const validArgs = totalArgs.slice(0, targetArity) const validLen = validArgs.filter(complement(isArgPlaceholder)).length if (validLen < targetArity) { return curry(fn, ...totalArgs) // as (typeof existingArgs) } else { return fn(...validArgs) } } } /****************************************************************************************************** * * CurryN Function * ******************************************************************************************************/ type RestrictParams< N extends number, Params extends any[], TN extends any[] = [], I extends any[] = [] > = { 0: RestrictParams, [...TN, Params[0]], Next> 1: TN }[ Pos extends N ? 1 : 0 ] type BuildExistingArgs any, LOOSE extends boolean = false> = RestrictParams> extends infer _ ? (LOOSE extends true ? Gaps>> : Gaps>) : never // 柯里化函数的基础类型 export type CurriedNFunctionOrReturnValue< EXPECTED_ARGS extends any[], RETURN_TYPE extends any, PROVIDED extends any[], LOOSE extends boolean = false > = // 判断柯里化函数的返回值需要准确的必需参数列表,所以这里的 GapsOf 始终是严格模式 GapsOf extends [any, ...any[]] ? CurriedNFunction : RETURN_TYPE export type CurriedNFunction< EXPECTED_ARGS extends any[], RETURN_TYPE extends any, PROVIDED extends any[], LOOSE extends boolean = false > = extends infer __ ? (LOOSE extends true ? Gaps>> : Gaps>) : never ) > // ConcatGaps 应该始终使用严格模式,以使后续追加的参数能够正确地被记录到 Provide 中 (...args: APPENDING_ARGS) => ConcatGaps extends infer ___ ? CurriedNFunctionOrReturnValue, LOOSE> : never type LooseCurryN = < ARITY extends number, FN extends (...args: any[]) => any, EXISTING_ARGS extends (BuildExistingArgs | []), EXPECTED_ARGS extends RestrictParams>, RETURN_TYPE extends ReturnType > (targetArity: ARITY, fn: FN, ...existingArgs: EXISTING_ARGS) => // TODO: 类型计算性能优化 // @ts-expect-error TypeScript 出于性能的担忧会提示“可能出错” CurriedNFunction type HPLooseCurryN = (targetArity: number, fn: AnyFunction, ...args: any[]) => AnyFunction /** * Internal curryN function - loose version * * Loose internal curry will pass all of the args it received to target function, * even if the arg's length is greater than specified arity. */ export const looseCurryN: HPLooseCurryN = (targetArity, fn, ...existingArgs) => { return (...appendingArgs) => { const totalArgs = existingArgs.map(innerArg => isArgPlaceholder(innerArg) ? (appendingArgs.length > 0 ? appendingArgs.shift() : innerArg) : innerArg ) totalArgs.push(...appendingArgs) const validArgs = totalArgs.slice(0, targetArity) const validLen = validArgs.filter(complement(isArgPlaceholder)).length if (validLen < targetArity) { return looseCurryN(targetArity, fn, ...totalArgs) // as (typeof existingArgs) } else { return fn(...totalArgs) } } } type CurryN = < ARITY extends number, FN extends (...args: any[]) => any, EXISTING_ARGS extends (BuildExistingArgs | []), EXPECTED_ARGS extends RestrictParams>, RETURN_TYPE extends ReturnType > (targetArity: ARITY, fn: FN, ...existingArgs: EXISTING_ARGS) => // TODO: 类型计算性能优化 // @ts-expect-error TypeScript 出于性能的担忧会提示“可能出错” CurriedNFunction type HPCurryN = (targetArity: number, fn: AnyFunction, ...args: any[]) => AnyFunction /** * Internal curryN function - strict version * * Strict internal curry will take exactly the required arity that specified, * redundant args will be ignored. */ export const curryN: HPCurryN = (targetArity, fn, ...existingArgs) => { return (...appendingArgs) => { const totalArgs = existingArgs.map(innerArg => isArgPlaceholder(innerArg) ? (appendingArgs.length > 0 ? appendingArgs.shift() : innerArg) : innerArg ) totalArgs.push(...appendingArgs) const validArgs = totalArgs.slice(0, targetArity) const validLen = validArgs.filter(complement(isArgPlaceholder)).length if (validLen < targetArity) { return curryN(targetArity, fn, ...totalArgs) // as (typeof existingArgs) } else { return fn(...validArgs) } } } // export const curry1 = (fn, ...args) => curryN(1, fn, ...args) // just for consistency // export const curry2 = (fn, ...args) => curryN(2, fn, ...args) // ... /****************************************************************************************************** * * Compose and Pipe Function * ******************************************************************************************************/ type AnyFunction = (...args: any[]) => any type ExtractFunctionArguments = Fn extends (...args: infer P) => any ? P : never type ExtractFunctionReturnValue = Fn extends (...args: any[]) => infer P ? P : never type Arbitrary = 'Respect: https://github.com/babakness/pipe-and-compose-types/blob/master/index.d.ts' type IsAny = Arbitrary extends O ? any extends O ? T : F : F type CastFn = FN extends AnyFunction ? FN : AnyFunction type CastFns = FNS extends AnyFunction[] ? FNS : AnyFunction[] type PipePlaceholder = AnyFunction & { __TYPE__: 'PipePlaceholder' } type RestrictFNS< FNS extends AnyFunction[], IsLeftToRight extends boolean = true, PreviousFunction extends AnyFunction = PipePlaceholder, InitalParams extends any[] = any[], ReturnType extends any = any, I extends any[] = [] > = { 'next': FNS extends [infer First, ...infer Rest] ? ( PreviousFunction extends PipePlaceholder ? // 第一次执行:将第一个函数的参数作为组合后函数的参数,第一个函数的返回值暂时作为组合后函数的返回值,同时可以供后续函数做参数类型判断 RestrictFNS< CastFns, IsLeftToRight, CastFn, ExtractFunctionArguments, ExtractFunctionReturnValue, Next > : ( // 第二次及之后的执行会到达这里,将返回值与当前的第一个函数的参数做类型判断 ReturnType extends ExtractFunctionArguments[0] ? // 如果当前函数的参数类型与上一个函数的返回值类型一致,则继续往后执行,并将当前函数的返回值作为组合后函数的返回值 RestrictFNS, IsLeftToRight, CastFn, InitalParams, ExtractFunctionReturnValue, Next> : ( // 如果当前函数的参数类型与上一个函数的返回值类型不一致,进一步判断上一个函数的返回值类型是否为 Any IsAny extends true ? // 如果上一个函数的返回值类型为 Any,继续往后执行 RestrictFNS, IsLeftToRight, CastFn, InitalParams, ExtractFunctionReturnValue, Next> : // 如果上一个函数的返回值类型不是 Any,则捕获错误 { ERROR: ['Return type ', ReturnType, 'doesn\'t comply with the input of', ExtractFunctionArguments[0]] ERROR_FUNCTION: ['( ', ...ExtractFunctionArguments, ' ) => ', ExtractFunctionReturnValue] POSITION: IsLeftToRight extends true ? ['Left to Right: ', Pos>, ' -> ', Pos] : ['Right to Left: ', Pos>, ' -> ', Pos] } ) ) ) : never 'done': (...args: InitalParams) => ReturnType }[FNS extends [] ? 'done' : 'next'] type Pipe = RestrictFNS type Compose = Reverse extends infer _ ? RestrictFNS>, false> : never type ComposeLeft = (...fns: FNS & Pipe extends AnyFunction ? FNS : never) => Pipe // NOTE: 另外一种 compose 实现 // @refer https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight // const compose = (...args) => value => args.reduceRight((acc, fn) => fn(acc), value) // 本质是一个闭包,直觉上不喜欢(虽然能够带来一些调试上的好处) // -> @refer https://www.freecodecamp.org/news/pipe-and-compose-in-javascript-5b04004ac937/ // 下面这种更符合函数式思维,实现上更接近数学定义 export const composeL: HPPipe = (...fns: any[]) => { const initialFunction = fns.shift() ?? asIs const composedFunction = fns.reduce((g, f) => (...args: any[]) => f(g(...args)), initialFunction) return composedFunction } type ComposeRight = (...fns: FNS & Compose extends AnyFunction ? FNS : never) => Compose export const composeR: HPCompose = (...fns: any[]) => (composeL as any)(...fns.reverse()) export const pipeL = composeL export const pipeR = composeR type NAryF = (...args: S) => R type UnaryF = (input: I) => O interface HPPipe { (): typeof asIs (fn1: NAryF): NAryF (fn1: NAryF, fn2: UnaryF): NAryF (fn1: NAryF, fn2: UnaryF, fn3: UnaryF): NAryF // eslint-disable-next-line max-len (fn1: NAryF, fn2: UnaryF, fn3: UnaryF, fn4: UnaryF): NAryF // eslint-disable-next-line max-len (fn1: NAryF, fn2: UnaryF, fn3: UnaryF, fn4: UnaryF, fn5: UnaryF): NAryF // eslint-disable-next-line max-len (fn1: NAryF, fn2: UnaryF, fn3: UnaryF, fn4: UnaryF, fn5: UnaryF, fn6: UnaryF): NAryF // eslint-disable-next-line max-len (fn1: NAryF, fn2: UnaryF, fn3: UnaryF, fn4: UnaryF, fn5: UnaryF, fn6: UnaryF, fn7: UnaryF): NAryF // eslint-disable-next-line max-len (fn1: NAryF, fn2: UnaryF, fn3: UnaryF, fn4: UnaryF, fn5: UnaryF, fn6: UnaryF, fn7: UnaryF, fn8: UnaryF): NAryF // eslint-disable-next-line max-len (fn1: NAryF, fn2: UnaryF, fn3: UnaryF, fn4: UnaryF, fn5: UnaryF, fn6: UnaryF, fn7: UnaryF, fn8: UnaryF, fn9: UnaryF): NAryF // eslint-disable-next-line max-len (fn1: NAryF, fn2: UnaryF, fn3: UnaryF, fn4: UnaryF, fn5: UnaryF, fn6: UnaryF, fn7: UnaryF, fn8: UnaryF, fn9: UnaryF, fn10: UnaryF): NAryF // eslint-disable-next-line max-len (fn1: NAryF, fn2: UnaryF, fn3: UnaryF, fn4: UnaryF, fn5: UnaryF, fn6: UnaryF, fn7: UnaryF, fn8: UnaryF, fn9: UnaryF, fn10: UnaryF, ...fns: Array>): NAryF } interface HPCompose { (): typeof asIs (fn1: NAryF): NAryF (fn2: UnaryF, fn1: NAryF): NAryF (fn3: UnaryF, fn2: UnaryF, fn1: NAryF): NAryF // eslint-disable-next-line max-len (fn4: UnaryF, fn3: UnaryF, fn2: UnaryF, fn1: NAryF): NAryF // eslint-disable-next-line max-len (fn5: UnaryF, fn4: UnaryF, fn3: UnaryF, fn2: UnaryF, fn1: NAryF): NAryF // eslint-disable-next-line max-len (fn6: UnaryF, fn5: UnaryF, fn4: UnaryF, fn3: UnaryF, fn2: UnaryF, fn1: NAryF): NAryF // eslint-disable-next-line max-len (fn7: UnaryF, fn6: UnaryF, fn5: UnaryF, fn4: UnaryF, fn3: UnaryF, fn2: UnaryF, fn1: NAryF): NAryF // eslint-disable-next-line max-len (fn8: UnaryF, fn7: UnaryF, fn6: UnaryF, fn5: UnaryF, fn4: UnaryF, fn3: UnaryF, fn2: UnaryF, fn1: NAryF): NAryF // eslint-disable-next-line max-len (fn9: UnaryF, fn8: UnaryF, fn7: UnaryF, fn6: UnaryF, fn5: UnaryF, fn4: UnaryF, fn3: UnaryF, fn2: UnaryF, fn1: NAryF): NAryF // eslint-disable-next-line max-len (fn10: UnaryF, fn9: UnaryF, fn8: UnaryF, fn7: UnaryF, fn6: UnaryF, fn5: UnaryF, fn4: UnaryF, fn3: UnaryF, fn2: UnaryF, fn1: NAryF): NAryF } export const compose: HPCompose = composeR export const pipe: HPPipe = pipeL /****************************************************************************************************** * * Memorize Function * ******************************************************************************************************/ type Memorize = (fn: FN, hasher: (...args: Parameters) => any) => (...args: Parameters) => ReturnType export const defaultMemorizeHasher = (...args: any[]): string => JSON.stringify(args) /** * Return a new function which bind to a cache map. * When the function is called, it will first check the cache map, if the result is found, return it. * Otherwise, call the function and cache the result. */ export const memorize: Memorize = (fn, hasher = defaultMemorizeHasher) => { const cache = new Map() hasher = hasher ?? defaultMemorizeHasher return (...args) => { const hash = hasher(...args) if (cache.get(hash) !== undefined) { cache.set(hash, fn(...args)) } return cache.get(hash) } } /****************************************************************************************************** * * Invoker Function * ******************************************************************************************************/ // // eslint-disable-next-line @typescript-eslint/ban-types // type getType = TARGET[KEY] // type getTargetArgs = // getType extends // infer _ ? // // TODO: 类型计算性能优化 // // @ts-expect-error TypeScript 出于性能的担忧会提示“可能出错” // [...RestrictParams>>, TARGET] : never // type InvokerCore = // // eslint-disable-next-line @typescript-eslint/ban-types // , TARGET extends Object> // (...args: ARGS) => // ReturnType, AnyFunction>> const invokerFactory = (curryFn: AnyFunction) => { return (arity: number, key: string) => { const invokerCore = (...args: any[]): any => { // curry function controlls how many args will be passed in const target = args[args.length - 1] if (target[key] === undefined) throw Error(`Can not find "${key}" method in target.'`) if (!isFunction(target[key])) throw Error(`"${key}" property in target is not a function.`) return target[key](...args.slice(0, args.length - 1)) } return curryFn(arity, invokerCore) as AnyFunction } } export const invoker = invokerFactory(curryN as AnyFunction) export const looseInvoker = invokerFactory(looseCurryN as AnyFunction) /****************************************************************************************************** * * Arity Function * ******************************************************************************************************/ type FallbackType = (fn: AnyFunction) => AnyFunction export const nAry = curry((n: number, fn) => curryN(n, fn)) export const looseNAry = curry((n, fn) => looseCurryN(n, fn)) export const quaternary: FallbackType = (fn) => curry((x, y, z, a) => fn(x, y, z, a)) // nAry(4, fn) export const looseQuaternary: FallbackType = (fn) => looseCurry((x, y, z, a, ...args) => fn(x, y, z, a, ...args)) // looseNAry(4, fn) export const ternary: FallbackType = fn => curry((x, y, z) => fn(x, y, z)) // nAry(3, fn) export const looseTernary: FallbackType = fn => looseCurry((x, y, z, ...args) => fn(x, y, z, ...args)) // looseNAry(3, fn) export const binary: FallbackType = fn => curry((x, y) => fn(x, y)) // nAry(2, fn) export const looseBinary: FallbackType = fn => looseCurry((x, y, ...args) => fn(x, y, ...args)) // looseNAry(2, fn) export const unary: FallbackType = fn => x => fn(x) export const looseUnary: FallbackType = fn => (x, ...args) => fn(x, ...args) type Tap = (fn: AnyFunction) => (...args: [...any[], T]) => T export const tap: Tap = fn => (...args) => { fn(...args) return args[0] } type Execute = (fn: FN, ...args: [...Parameters, ...any[]]) => ReturnType export const execute: Execute = (fn, ...args) => fn(...args) /****************************************************************************************************** * * Quick Tests * ******************************************************************************************************/ /* arguments num controller & curry test */ // const add = (x, y, z) => { console.log(x, y, z) } // unary(add)(1, 2, 3) // 1, undefined, undefined // binary(add)(1, 2, 3) // 1, 2, undefined // nAry(1, add)(1, 2, 3) // 1, undefined, undefined // nAry(2, add)(1, 2, 3) // 1, 2, undefined // nAry(3, add)(1, 2, 3) // 1, 2, 3 // looseUnary(add)(1, 2, 3) // 1, 2, 3 // looseBinary(add)(1, 2, 3) // 1, 2, 3 // looseNAry(1, add)(1, 2, 3) // 1, 2, 3 // looseNAry(2, add)(1, 2, 3) // 1, 2, 3 // looseNAry(3, add)(1, 2, 3) // 1, 2, 3 // const gg = (a, b) => { // console.warn(a, b) // } // const ff = (a, b) => { // curry(gg)(a) // } // ff(1)