博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Ramada] Build a Functional Pipeline with Ramda.js
阅读量:4990 次
发布时间:2019-06-12

本文共 2150 字,大约阅读时间需要 7 分钟。

We'll learn how to take advantage of Ramda's automatic function currying and data-last argument order to combine a series of pure functions into a left-to-right composition, or pipeline, with Ramda's pipe function.

 

A simple example will take 'teams' array and output the best score team's name. We use 'R.sort', 'R.head' and 'R.prop' to get job done:

const teams = [  {name: 'Lions', score: 5},  {name: 'Tigers', score: 4},  {name: 'Bears', score: 6},  {name: 'Monkeys', score: 2},];const getTopName = function(teams){  const sorted = R.sort( (a,b) => b.score > a.score, teams);  const bestTeam = R.head(sorted);  const name = R.prop('name', bestTeam);  return name;}const result = getTopName(teams)console.log(result)

 

One thing in Ramda which is really cool that, for example, 'R.sort' takes two arguements, if you don't passin the second arguement which is 'teams', it will then return a function, so that it enable you currying function and take second arguement as param.

const teams = [  {name: 'Lions', score: 5},  {name: 'Tigers', score: 4},  {name: 'Bears', score: 6},  {name: 'Monkeys', score: 2},];const getBestTeam = R.sort( (a,b) => b.score > a.score);const getTeamName = R.prop('name');const getTopName = function(teams){  const sorted = getBestTeam(teams);  const bestTeam = R.head(sorted);  const name = getTeamName(bestTeam);  return name;}const result = getTopName(teams)console.log(result)

We will still get the same result.

 

Use 'R.pipe' to chain function together

In functional programming or lodash (_.chain), we get used to write chain methods, in Ramda, we can use R.pipe():

const teams = [  {name: 'Lions', score: 5},  {name: 'Tigers', score: 4},  {name: 'Bears', score: 6},  {name: 'Monkeys', score: 2},];const getBestTeam = R.sort( (a,b) => b.score > a.score);const getTeamName = R.prop('name');const getTopName = R.pipe(  getBestTeam,  R.head,  getTeamName);/*const getTopName = function(teams){  const sorted = getBestTeam(teams);  const bestTeam = R.head(sorted);  const name = getTeamName(bestTeam);  return name;}*/const result = getTopName(teams)console.log(result)

 

转载于:https://www.cnblogs.com/Answer1215/p/5801424.html

你可能感兴趣的文章
css单位pr,em,与颜色
查看>>
Angularjs笔记(三)
查看>>
@ControllerAdvice 标签为起作用
查看>>
lambda
查看>>
ubuntu16.04下使用python3开发时,安装pip3与scrapy,升级pip3
查看>>
python网络编程基础
查看>>
selenium+maven+testng+IDEA+git自动化测试环境搭建(二)
查看>>
Mini2440 UART原理及使用
查看>>
Linux学习第六篇之文件处理命令ln(链接命令)
查看>>
thinkphp5 tp5 七牛云 上传图片
查看>>
Windows 7 x64 安装Windows SDK 7.1失败的原因及解决方法
查看>>
VM下Linux网卡丢失(pcnet32 device eth0 does not seem to be ...)解决方案
查看>>
第一阶段意见汇总以及改进
查看>>
再说virtual
查看>>
随笔:技术流可以这样写博客
查看>>
[优化]JavaScript 格式化带有占位符字符串
查看>>
打JAR包
查看>>
大图轮播
查看>>
UNIX环境高级编程读书笔记
查看>>
java awt 乱码问题
查看>>