首页 > 解决方案 > 比较两个数字,ramdajs

问题描述

说我有两个功能

const getMeanPrice = R.....

const getLastPrice = R...

我应该使用哪些函数来检查一个值是否大于另一个?

const isLastPriceHigherThanMeanPrice = R. ???

有 R.gt https://ramdajs.com/0.22.1/docs/#gt

但它只接受两个数字。需要接受两个功能的东西。喜欢

R.somefunc(getMeanPrice, getLastPrice)(prices) => boolean

标签: ramda.js

解决方案


lift将对值进行操作的函数转换为对值容器进行操作的函数。例如,

lift (gt) ([8, 1, 6], [3, 5, 7]) 
//=> [8 > 3, 8 > 5, 8 > 7, 1 > 3, 1 > 5, 1 > 7, 6 > 3, 6 > 5, 6 > 7]
//=> [true,  true,  true,  false, false, false, true,  true,  false]

返回某个类型的函数可以被认为是该类型元素的容器,所以如果我们lift R.gt,它也会对函数进行操作。因此:

// Dummy implementations
const getMeanPrice = R.mean
const getLastPrice = R.last

const isLastPriceHigherThanMeanPrice = R.lift (R.gt) (getLastPrice, getMeanPrice)

console .log ([
  [4, 5, 6],
  [6, 5, 4],
  [8, 6, 7, 5, 3, 0, 9],
  [8, 6, 7, 5, 3, 0]
].map(a => `[${a.join(', ')}] ==> ${isLastPriceHigherThanMeanPrice(a)}`).join('\n'))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

lift将适用于任何Apply类型,即具有合法apmap定义功能的类型。这包括数组、函数和许多其他有用的类型,例如MaybeEitherFuture和许多其他的大多数实现。


推荐阅读