javascript - 避免在 rambda 中重复参数
问题描述
import { pipe } from 'rambda';
function readFile(filePath) { // reading the file return fileContents }
function editFile(fileContents) { // edit the file return newFileContents }
function writeFile(fileContents, filePath) { // write content }
function manipulateFile(filePath) {
return writeFile(pipe(readFile, editFile)(filePath))(filePath);
}
有什么方法可以避免filePath
参数重复manipulateFile
?
理想情况下,我想像这样管道它。但filePath
不会提供给writeFile
function manipulateFile(filePath) {
return pipe(
readFile,
editFile,
writeFile
)(filePath)
}
解决方案
您可以使用chain
组合器将相同的参数传递给多个嵌套函数调用。
以下是JavaScript 中常见组合子的摘录:
const S_ = f => g => x => f (g (x)) (x)
[...]
姓名 # 哈斯克尔 拉姆达 避难所 签名 链 S_ (=<<)
chain
chain
(a → b → c) → (b → a) → b → c
为了使其在这里的相关性更加明显,请考虑这一点-您manipulateFile
可以将其重写为:
function manipulateFile(filePath) {
const f = writeFile;
const g = pipe(readFile, editFile);
const x = filePath;
return f (g (x)) (x);
}
它与主体完全匹配,S_
因此可以表示为S_(f)(g)(x)
。
使用Rambdachain
,您可以使用:
import { pipe, chain } from 'ramda';
function readFile(filePath) { // reading the file return fileContents }
function editFile(fileContents) { // edit the file return newFileContents }
function writeFile(fileContents, filePath) { // write content }
function manipulateFile(filePath) {
return chain(writeFile, pipe(readFile, editFile))(filePath);
}
或将其减少为无点:
const manipulateFile = chain(writeFile, pipe(readFile, editFile));
似乎Rambdachain
的工作方式与 Ramda 不同。
推荐阅读
- android - React-Native Element 在滚动时改变大小
- python - 谷歌云如何获得授权?
- azure - Invoke-AzureRmVMRunCommand 参数传递突然失败
- f# - 在 F# 中存储对局部变量的引用
- java - 如何在java中获取特定日期的UTC值
- sql - 根据字段的不同计数设置列
- python-3.x - 为什么基于 if 的测试和基于 lambda 的测试之间的返回值差异
- javascript - 如何向 javascript dragElement 添加约束
- html - 白色 X 出现在我拥有的所有浏览器的灰色框中,但 iPad 上的 Safari 除外。我犯了错误还是Safari?
- javascript - three.js - 从 Matrix4 获取 X、Y、Z 旋转值