[Ramada] Build a Functional Pipeline with Ramda.js

來源:互聯網
上載者:User

標籤:

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)

 

[Ramada] Build a Functional Pipeline with Ramda.js

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.