javascript - ramda/函数式编程 - 基于条件的不同逻辑
问题描述
我是函数式编程的新手,我想浏览一个集合并根据条件找到一个元素。条件如下,但我想知道是否有更优雅的方式以函数方式编写它(下面使用 Ramda):
import * as R from "ramda";
const data = [{x: 0, y: 0} , {x: 1, y: 0}];
//return the cell which matches the coord on the given orientation
function findCell(orientation, coord) {
const search = R.find(cell => {
if (orientation === "x") {
return cell.x === coord;
} else {
return cell.y === coord;
}
});
return search(data);
}
findCell("x", 0);
有没有更优雅的方式在 Ramda 或其他一些函数式 JS 库中编写这个谓词?
解决方案
R.propEq 是您正在寻找的合适谓词(按属性值查找)。使用 R.pipe 创建一个接受属性和值的函数,将它们传递给 R.propEq,并返回一个带有谓词的 R.find 函数。
const { pipe, propEq, find } = R;
const findCell = pipe(propEq, find);
const data = [{x: 0, y: 0} , {x: 1, y: 0}];
const result = findCell('x', 0)(data);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
你可以使用 vanilla JS 做同样的事情Array.find()
:
const findCell = (prop, value, arr) => arr.find(o => o[prop] === value)
const data = [{x: 0, y: 0} , {x: 1, y: 0}];
const result = findCell('x', 0, data);
console.log(result);
推荐阅读
- javascript - 使用“crypto-js”编码并使用“crypto”解码(节点)
- java - 检查 ListView
包含一个字符串 - JavaFX - magento2 - Magento2 中锚定类别的产品计数
- reactjs - 如何在antd的嵌套表中放置一个加载器?
- python - 文件未保存在 Python 的正确目录中
- javascript - 如何在类构造中实现各种方法
- android - 如何一个接一个地垂直对齐芯片
- struct - DFS 在结构向量的邻接列表中查找连通性
- javascript - 如何获取单击的元素的最高父元素,该元素仍然是添加事件侦听器的元素的子元素?
- c++ - 如何从 2d QUEUE 获取值