[Ramda] Eliminate Function Arguments (Point-Free Style) with Ramda's Converge

本文介绍如何使用Ramda库中的converge函数来重构代码,实现Point-Free风格的编程,提高函数组合和构造的灵活性。通过具体示例展示了如何判断数组中第一个元素是否为最大值。

When doing comparisons inside of functions, you end of relying heavily on the argument passed into the function. Ramda's converge allows you to do comparisons in a Point-Free style allowing you more flexibility with composing and constructing functions. This lesson walks through refactoring a function to Point-Free style using Ramda's Converge.

 

For example we want to find the whether the first item of an array is the biggest number:

const shouldBeTrue = [6, 3, 4, 5, 2, 1]
const shouldBeFalse = [3, 4, 5, 2, 1]

const isFirstBiggest = (xs) => xs[0] == xs.sort((a, b) => b - a)[0]

console.log(isFirstBiggest(shouldBeTrue)) // true
console.log(isFirstBiggest(shouldBeFalse)) // false

In the code we can see this:

const isFirstBiggest = (xs) => xs[0] === xs.sort((a, b) => b - a)[0]

You can find that, param 'xs' appears both on the left and right side of euqals sign.

If match this partten, we actually can use 'converge' from  Ramda.

invoked, this new function is applied to some arguments, each branching function is applied to those same arguments. The results of each branching function are passed as arguments to the converging function to produce the return value.

For example:

const shouldBeTrue = [6, 3, 4, 5, 2, 1]
const shouldBeFalse = [3, 4, 5, 2, 1]

import {
  converge, equals, head, sort, descend, identity, compose
}
from 'ramda'

const biggestNumberOfArray = compose(
  head,
  sort(descend(identity))
);
const isFirstBiggest = converge(
  equals, [
    head,
    biggestNumberOfArray
  ]
);

// xs =>
//     xs[0] == xs.sort((a, b) => b - a)[0]



console.log(isFirstBiggest(shouldBeTrue))
console.log(isFirstBiggest(shouldBeFalse))

So in the code:

converge(
  equals, [
    head,
    biggestNumberOfArray
  ]
)

converge takes two params, first params is 'R.equals'. It tells what should do with the second param. Here is checking whether they are equal.

Second param is an array, take tow expersions.

R.head --> xs[0]
biggestNumberOfArray --> xs.sort((a,b) => b-a)[0]

 

More example:

var average = R.converge(R.divide, [R.sum, R.length])
average([1, 2, 3, 4, 5, 6, 7]) //=> 4

var strangeConcat = R.converge(R.concat, [R.toUpper, R.toLower])
strangeConcat("Yodel") //=> "YODELyodel"

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值