ramda/functional 编程 - 基于条件的不同逻辑
ramda/functional programming - different logic based on condition
我是函数式编程的新手,我想遍历一个集合并根据条件找到一个元素。条件如下,但我想知道是否有更优雅的方式以功能方式编写它(下面使用 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,并且 returns 一个带有谓词的 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);
我是函数式编程的新手,我想遍历一个集合并根据条件找到一个元素。条件如下,但我想知道是否有更优雅的方式以功能方式编写它(下面使用 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,并且 returns 一个带有谓词的 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);