Simplified rearg snippet
This commit is contained in:
@ -2,16 +2,10 @@
|
|||||||
|
|
||||||
Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.
|
Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.
|
||||||
|
|
||||||
Use `Array.reduce()` and `Array.indexOf()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
|
Use `Array.map()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const rearg = (fn, indexes) => (...args) =>
|
const rearg = (fn, indexes) => (...args) => fn(...indexes.map(idx => args[idx]));
|
||||||
fn(
|
|
||||||
...args.reduce(
|
|
||||||
(acc, val, i) => ((acc[indexes.indexOf(i)] = val), acc),
|
|
||||||
Array.from({ length: indexes.length })
|
|
||||||
)
|
|
||||||
);
|
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -1,8 +1,2 @@
|
|||||||
const rearg = (fn, indexes) => (...args) =>
|
const rearg = (fn, indexes) => (...args) => fn(...indexes.map(idx => args[idx]));
|
||||||
fn(
|
|
||||||
...args.reduce(
|
|
||||||
(acc, val, i) => ((acc[indexes.indexOf(i)] = val), acc),
|
|
||||||
Array.from({ length: indexes.length })
|
|
||||||
)
|
|
||||||
);
|
|
||||||
module.exports = rearg;
|
module.exports = rearg;
|
||||||
|
|||||||
Reference in New Issue
Block a user