es-toolkit icon indicating copy to clipboard operation
es-toolkit copied to clipboard

Implement Pipe function

Open risalfajar opened this issue 8 months ago • 2 comments

Lodash has chain function, but I learned that it's impossible to implement because of tree-shaking. Maybe instead of chain, pipe can be implemented instead.

Taking inspiration from Remeda:

R.pipe(
  [1, 2, 3, 4],
  R.map((x) => x * 2),
  (arr) => [arr[0] + arr[1], arr[2] + arr[3]],
); // => [6, 14]

Source code

Related issue: #415

risalfajar avatar May 18 '25 04:05 risalfajar

This would be very handy

amrsalama avatar Sep 15 '25 19:09 amrsalama

A pipe function would be a great addition, especially considering that the JavaScript pipe operator proposal looks more and more like it will be stuck in Stage 2 forever.

A hypothetical usage example:

const mostRecentlyFinishedTasks = pipe
  tasks,
  (tasks) => tasks.filter(t => t.done),
  (tasks) => sortBy(tasks, -task.completedAt),
  (tasks) => take(tasks, 3),
);

which would be basically equivalent to the following code using the existing flow:

const mostRecentlyFinishedTasks = flow(
  (tasks) => tasks.filter(t => t.done),
  (tasks) => sortBy(tasks, -task.completedAt),
  (tasks) => take(tasks, 3),
)(tasks);

The difference is that pipe would not build up a temporary function (only to throw it away right after). For TypeScript users, pipe would also provide better type inference because the type of the initial argument can be used to infer the argument type of the first function, i.e.:

// Single-function overload
function pipe<T, R>(input: T, f1: (arg: T) => R): R;

// Two-function overload
function pipe<T, R1, R>(input: T, f1: (arg: T) => R1, f2: (arg: R1) => R): R;

// ...

denisw avatar Oct 17 '25 12:10 denisw