@vlr/fp-tools

A set of functional programming tools.

Usage no npm install needed!

<script type="module">
  import vlrFpTools from 'https://cdn.skypack.dev/@vlr/fp-tools';
</script>

README

@vlr/fp-tools

A set of functional programming conversions

mapWith

This converts a function with one argument into a function with array of arguments of that type. For example, if you have to make such functions:

function doSmth(a: number): string { // do smth … }

function doSmthForAll(a: number[]): string[] { return a.map(doSmth); }

instead of writing second function, you can make it using mapWith

const doSmthForAll = mapWith(doSmth);

It will also work like this if the first function has several arguments, but in this case converted function will have first parameter converted from single to array, the rest of parameters will stay single and will be applied to each element of that array.

function doSmth(a: number, b: number): string { // do smth … }

function doSmthForAll(a: number[], b: number): string[] { return a.map(a1 => doSmth(a1, b)); }

You can create that function using the same call to mapWith. Also, in case when there is no need to save the resulting function, it can be just called right away.

function doSmth(a: number, b: number): string { return (a + b).toString(); }

const smth: string[] = mapWith(doSmth)([1, 2, 3], 4); // ["5", "6", "7"]

partial

Where it is applicable.

Sometimes you have to use functions having 2 arguments in a one-argument context. for example, here employeeMatches is used like that

export function findEmployeeById(employees: Employee[], id: EmployeeId): Employee {
    return employees.find(employee => employeeMatches(employee, id));
}

function employeeMatches(employee: Employee, id: EmployeeId): boolean {
    return employeeIdEquals(employee.id, id);
}

Suggestion

is to shorten partial application a bit, just like that:


export function findEmployeeById(employees: Employee[], id: EmployeeId): Employee {
    // instead of this
    // return employees.find(employee => employeeMatches(employee, id));
    // write this
       return employee.find(partial(employeeMatches, id));
    // or this
       return employee.find(partial2(employeeMatches, id));
}

Here "partial2", means that you fix the target function to having 2 parameters exactly. As well as "partial3" is fixed to 3 and "partial4" to 4 correspondingly. And "partial" has overrides for any amount of arguments in target function up to 4, which is a bit less strict, but it has limitation, you can't predefine all arguments. I could not make safe typing for that case.

Alternatively

Can use lodash _.partialRight, which is a bit longer definition, larger package, and yes, has that defect with unsafe typing for no-arguments return function.