简体   繁体   English

如何使用Lodash在JavaScript中以功能方式实现此目的?

[英]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. 我正在使用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? 但是我只是想知道在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 如果这种提琴不起作用,请使用以下jsbin: http ://jsbin.com/gicocivife/edit?js,console

Pay attention to ugly curry(flip(get)) and curry(flip(slise)) . 注意丑陋的curry(flip(get))curry(flip(slise)) The problem is that functions in lodash has such an order of arguments that prevents you from composition. 问题是lodash中的函数具有这样的参数顺序,使您无法进行组合。 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. 我建议看一下Ramda。 Not only from my point of view this is a great library for FP. 不仅从我的角度来看,这对于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! 它还具有镜头,这是一个了不起的事情!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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