From f74c10be6069e771c874505f6bd94011450ddd87 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 28 Jan 2018 15:04:21 +0200 Subject: [PATCH] Add rearg --- snippets/rearg.md | 25 +++++++++++++++++++++++++ tag_database | 1 + 2 files changed, 26 insertions(+) create mode 100644 snippets/rearg.md diff --git a/snippets/rearg.md b/snippets/rearg.md new file mode 100644 index 000000000..f58ea2f58 --- /dev/null +++ b/snippets/rearg.md @@ -0,0 +1,25 @@ +### rearg + +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`. + +```js +const rearg = (fn, indexes) => (...args) => + fn( + ...args.reduce( + (acc, val, i) => ((acc[indexes.indexOf(i)] = val), acc), + Array.from({ length: indexes.length }) + ) + ); +``` + +```js +var rearged = rearg( + function(a, b, c) { + return [a, b, c]; + }, + [2, 0, 1] +); +rearged('b', 'c', 'a'); // ['a', 'b', 'c'] +``` diff --git a/tag_database b/tag_database index 8a8a891bc..18fa151c3 100644 --- a/tag_database +++ b/tag_database @@ -187,6 +187,7 @@ randomIntArrayInRange:math,utility,random randomIntegerInRange:math,utility,random randomNumberInRange:math,utility,random readFileLines:node,array,string +rearg:adapter,function redirect:browser,url reducedFilter:array reduceSuccessive:array,function