zoukankan      html  css  js  c++  java
  • [Ramada] Build a Functional Pipeline with Ramda.js

    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)
  • 相关阅读:
    HDU_1846 Brave Game(sg函数简化版)
    POJ 3225 Help with Intervals(线段树)
    ZOJ_3501 Roman Order
    HDU_1527 取石子游戏(威佐夫博弈)
    HDU_2112 HDU Today(DIjkstra + map映射)
    HDU_3339 In Action(Dijkstra + DP)
    单链表的实现(课本上的算法)
    haproxy 基于 uri 实现调度
    haproxy 基于 cookie 实现 session 绑定
    [转]ASP.NET 虚拟主机安全漏洞解决方案
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5801424.html
Copyright © 2011-2022 走看看