简体   繁体   中英

How to do this in a functional way in JavaScript using Lodash?

I'm new to functional programming and I'm trying to refactor my code to have no side-effect.

let keywords = _.get(content, '[0].keywords', []);
keywords = keywords.slice(0, config.keywordLimit);

I'm using lodash. I believe you can just chain these two methods and be something like this.

const keywords = _.get(content, '[0].keywords', []).slice(0, config.keywordLimit);

But I'm just wondering if there's a more functional way of doing this in JavaScript?

Basically, functional style is all about composition. Here is a sample:

 var get = _.curry(_.flip(_.get), 3); var slice = _.curry(_.flip(_.slice), 3); var comp = function(f, g) { return function(x) { return f(g(x)); } }; var config = { keywordLimit: 2 }; var program = comp( slice(config.keywordLimit, 0), get([], 'x') ) var x = program({ x: ['abc', 'qwe', 'sdf'] }); console.log(x); 
 <script src="https://raw.githubusercontent.com/lodash/lodash/4.17.2/dist/lodash.min.js"></script> 

In case, this fiddle doesn't work, here's jsbin: http://jsbin.com/gicocivife/edit?js,console

Pay attention to ugly curry(flip(get)) and curry(flip(slise)) . The problem is that functions in lodash has such an order of arguments that prevents you from composition. Your function expects data to work with, right? Thus, the argument for this data must be the last one. Therefore, you can compose functions. I'd recommend to look at Ramda. Not only from my point of view this is a great library for FP. Here's the same example written with it.

var config = { keywordLimit: 2 };

var program = compose(
  slice(0, config.keywordLimit),
  view(lensProp('x'))
)

program({
  x: ['abc', 'qwe', 'sdf']
});

The thing is, functions are curried by default. Thus, the partial application comes naturally. It also features Lenses, which is an awesome thing!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM