remeda / remeda

A utility library for JavaScript and TypeScript.
http://remedajs.com
MIT License
4.42k stars 136 forks source link

Explain how the 3rd (data) param works for lazy invocations #729

Open mass8326 opened 3 months ago

mass8326 commented 3 months ago

Description

The parameters passed into map() do not match between data-first/data-last vs pipe/piped.

It seems to happen in the latest version v2.0.9 with map() and seems to go as far back as v1.0.0 with map.indexed()

Is this expected behavior? I didn't seem to catch this in the documentation for either map() or pipe().

REPL: https://stackblitz.com/edit/remeda-piped-map-issue?file=index.js

Input

import * as remeda from 'remeda';

console.log('Data first');
remeda.map([1, 2, 3, 4], (val, i, arr) => console.log(arr));

console.log('Data last');
remeda.map((val, i, arr) => console.log(arr))([1, 2, 3, 4]);

console.log('Pipe');
remeda.pipe(
  [1, 2, 3, 4],
  remeda.map((val, i, arr) => console.log(arr))
);

console.log('Piped');
remeda.piped(remeda.map((val, i, arr) => console.log(arr)))([1, 2, 3, 4]);

Output

Data first
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]
Data last
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]
Pipe
[ 1 ]
[ 1, 2 ]
[ 1, 2, 3 ]
[ 1, 2, 3, 4 ]
Piped
[ 1 ]
[ 1, 2 ]
[ 1, 2, 3 ]
[ 1, 2, 3, 4 ]
cjquines commented 3 months ago

this is expected behavior. for lazy functions, the third parameter is always the array as it is being built, because otherwise it can't be lazy

cjquines commented 3 months ago

i'm not sure where we can document this better—we have this pattern for nearly all of our lazy indexed functions.

eranhirsch commented 3 months ago

You can disable lazy invocation by wrapping a data-first call:

remeda.pipe(
  [1, 2, 3, 4],
  ($) => remeda.map($, (val, i, arr) => console.log(arr))
);

@cjquines, we could add an article to the top of the docs explaining this behavior. I'll remove the wontfix tag so we can track this, but I admit it's gonna be pretty low-pri as I wouldn't add an article about this before we also add other articles first.