ngxtension / ngxtension-platform

Utilities for Angular
https://ngxtension.netlify.app/
MIT License
609 stars 88 forks source link

feature: add flattenArray() operator #207

Open Laurens-makel opened 10 months ago

Laurens-makel commented 10 months ago

I'd like to propose the flattenArray() array operator, which is great when working with two-dimensional arrays.

It should take an optional parameter depth, which defaults to 1, just like the .flat() method does.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat image

Currently

of([ [1,2], [3,4] ]).pipe(
  map(array => array.flat())
);
// [1, 2, 3, 4]

Operator

import { map } from 'rxjs';

export const flattenArray = <T>(depth=1) =>
    map((array: T[]) => array.flat(depth));

With operator:

of([ [1,2], [3,4] ]).pipe(
  flattenArray()
);
// [1, 2, 3, 4]
endlacer commented 10 months ago

Considering that 'filterArray,' 'mapArray,' 'reduceArray,' etc., already exist, this would be suitable. However, I believe these one-line replacement methods could unnecessarily complicate understanding for your coworkers.

LcsGa commented 6 months ago

I think that creating such operators is not a very good idea. map is made to transform the previous observable into a new one, with a transform function.

In my opinion, what we should aim for is composition. It is more flexible as it is not tied to RxJS and it aligns with the RxJS core team's way of doing. So here, instead of ̀flattenArray, we could do this:

function flatten<T>(depth?: number) {
  return (arr: T[]) => arr.flat(depth);
}

const arr = [[1, 2], [3, [4]]];

of(arr)
  .pipe(map(flatten(2)))
  .subscribe(console.log); // [1, 2, 3, 4]

console.log(flatten()(arr)); // [1, 2, 3, [4]]