@bemedev/function-swap
v0.2.5
Published
A TypeScript utility that lets you remap a function's parameters by swapping their order or decomposing them into named keys — without changing the original function signature.
Downloads
1,454
Maintainers
Readme
@bemedev/function-swap
A TypeScript utility that lets you remap a function's parameters by swapping their order or decomposing them into named keys — without changing the original function signature.
Installation
pnpm add @bemedev/function-swap
pnpm add -P @bemedev/decompose # Peer dependency[!NOTE]
@bemedev/decomposeis a peer dependency of@bemedev/function-swapand must be installed in your project.
Usage
import { swap } from '@bemedev/function-swap';
// Original function: (a, b, c) => string
const greet = (first: string, last: string, title: string) =>
`${title} ${first} ${last}`;
// Remap: call as (title, last, first) instead
const swappedGreet = swap(greet)('[2]', '[1]', '[0]');
swappedGreet('Dr.', 'Smith', 'John'); // => "Dr. John Smith"Aliases
import { swap } from '@bemedev/function-swap';
swap.fromFunction(fn); // same as swap(fn)
swap.fromFn(fn); // same as swap(fn)swap.fromParameters / swap.fromParams
swap.fromParameters (or swap.fromParams) is the type-first variant.
Instead of wrapping an existing function, you declare the target
parameter shape P as a tuple type parameter, then provide decomposed
key selectors, and finally pass in the implementation function.
swap.fromParams<P>()(...keys)(fn) => fn| Step | What you provide | What you get |
| ----------- | ---------------------------------------------- | ------------------------ |
| <P>() | Tuple parameter type P as a generic | A key-selector builder |
| (...keys) | Decomposed key strings / nested maps | A typed function builder |
| (fn) | Implementation matching the resolved signature | The function fn |
Example — build a typed function over parameter shapes:
import { swap } from '@bemedev/function-swap';
type UserParam = [{ data: string; age: number }, number];
// Select target parameter paths
const swapFn = swap.fromParams<UserParam>()('[1]', '[0].data', '[0].age');
const fn = swapFn(
(length, data, age) => `${length}:${data.toUpperCase()}-${age * 2}`,
);
fn(5, 'alice', 30); // => "5:ALICE-60"swap(fn).constraint
swap(fn).constraint lets you define explicit parameter maps between
target input parameter types P and source function parameters.
import { swap } from '@bemedev/function-swap';
const subtract = (a: number, b: number) => a - b;
// Swap arguments [0] and [1] with a constraint map
const swappedSubtract = swap(subtract).constraint<[number, number]>()({
'[0]': '[1]',
'[1]': '[0]',
});
swappedSubtract(2, 10); // => 8 (10 - 2)[!NOTE]
DecomposeStringis not partial at runtime. Even though TypeScript optional property syntax (?) allows omitting keys in the constraint mapping object, all decomposed keys required by the target function must be mapped. Omitting required keys will result inundefinedvalues during argument recomposition and will fail at runtime if the target function expects them.
Zero-Parameter & Empty Mappings
Functions without parameters or callers requiring empty mapping
configurations are supported out of the box by swap and
swap(fn).constraint:
import { swap } from '@bemedev/function-swap';
const getStatus = () => 'active';
// Direct swap for zero-parameter function
const swappedStatus = swap(getStatus)();
swappedStatus(); // => "active"
// Empty constraint mapping for zero-parameter or ignored arguments
const constrainedStatus = swap(getStatus).constraint<[string]>()({});
constrainedStatus('ignored'); // => "active"Exported Types
@bemedev/function-swap exports the following utility types and function
signatures:
Core Function & Builder Types
AnyFunction: Generic function signature type(...args: any[]) => any.FunctionSwap: Function signature forswap(fn).FunctionSwapLevel2<F>: Return type ofswap(fn)providing key-selector mapping and.constraint<P>().FunctionSwapParams: Function signature forswap.fromParameters/swap.fromParams.
Parameter Selection & Mapping Types
ObjectFrom<T extends string>: Union type of string key pathTor nested key mapObjectFromMap<T>.ObjectFromMap<T extends string>: Recursive dictionary mapping string keys toObjectFrom<T>.ResolveObjectFrom<P, D>: Resolves argument type from key selectorPusing decomposed mapD.ResolveParamArray<P, D>: Maps tuple of key selectorsPto resolved parameter types.
Decomposition & Helper Types
Decompose<T>: Decomposes object or tuple typeTinto dot-separated key-value pairs (with leading dot removed).DecomposedKeys<T>: Extracts all string key paths resulting from decomposing typeT.DecomposedParameterKeys<F>: Helper extracting decomposed key paths from parameters of functionF.DecomposedMap<F>: Raw decomposed type representation of parameters of functionF.AllowedNames<Base, Condition>: Filters property keys ofBasematching typeCondition.SubType<Base, Condition>: Constructs a subtype ofBasecontaining only properties matching typeCondition.DecomposeString<T, Decomposed>: Maps decomposed target parameter key paths to matching source key paths. Note: Not partial at runtime.
Licence
MIT
CHANGE_LOG
Read CHANGELOG.md for more details about the changes.
Auteur
chlbri ([email protected])
