Array display function in lodash

I have this piece of javascript code:

function arrayMapper(mappingFunc) {
  return items => items.map(mappingFunc);
}

function fooTransformer(tem) {
  return (...); // do something with item and returns a value
}

function barTransformer(tem) {
  return (...); // do something with item and returns a value
}

const foosTransformer = arrayMapper(fooTransformer);
const barsTransformer = arrayMapper(barTransformer);
(...)
foosTransformer([1, 2, 3]);

I was wondering if something like my function arrayMapperwould initially exist in something like lodash, just so as not to reinvent the wheel.

+4
source share
2 answers

Basically you do the currying map function (right).

Lodash allows you to do this:

const mapper = _.curryRight(_.map);

const square = mapper(x => x ** 2);

console.log(
  square([1, 2, 3]) // [1, 4, 9]
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Run codeHide result

Saying this, it is certainly overkill to put together an entire library for such a small function. Perhaps if you are using npm, you can simply npm install lodash.curryright lodash.mapuse only those that may still be unnecessary.

+2
source

chain, map value()

var arr = [1, 2, 3];
var add1 = e => e + 1;
var add2 = e => e + 2;

var result = _.chain(arr).map(add1).map(add2).value()
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
Hide result

ES6 reduce() , .

var arr = [1, 2, 3];
var add1 = e => e + 1;
var add2 = e => e + 2;

function arrayMapper(arr, ...mappingFunc) {
  return mappingFunc.reduce((r, f) => (r = Array.prototype.map.call(r, f), r), arr)
}


var result = arrayMapper(arr, add1, add2)
console.log(result)
Hide result
0

Source: https://habr.com/ru/post/1677369/


All Articles