【发布时间】:2018-04-01 10:21:15
【问题描述】:
我正在使用ramda 和data.task 编写一个小型实用程序,它可以从目录中读取图像文件并输出它们的大小。我让它像这样工作:
const getImagePath = assetsPath => item => `${assetsPath}${item}`
function readImages(path) {
return new Task(function(reject, resolve) {
fs.readdir(path, (err, images) => {
if (err) reject(err)
else resolve(images)
})
})
}
const withPath = path => task => {
return task.map(function(images) {
return images.map(getImagePath(path))
})
}
function getSize(task) {
return task.map(function(images) {
return images.map(sizeOf)
})
}
const getImageSize = dirPath => compose(getSize, withPath(dirPath), readImages)
问题在于 withPath 函数将正确的图像路径添加到图像文件名,但强制我的 api 两次传入 directoryName:一次用于读取文件,第二次用于读取路径。这意味着我必须像这样调用getImageSize 函数:
const portfolioPath = `${__dirname}/assets/`
getImageSize(portfolioPath)(portfolioPath).fork(
function(error) {
throw error
},
function(data) {
console.log(data)
}
)
有没有办法将dirname 作为参数只传递一次?我希望 api 像这样工作:
getImageSize(portfolioPath).fork(
function(error) {
throw error
},
function(data) {
console.log(data)
}
)
【问题讨论】:
-
我现在在我的手机上,所以无法真正测试,但您可以查看
chain如何处理函数:chain(f, g)(x) => f(g(x), x)。 -
嘿@ScottSauyet - 希望引起你的注意。我解决了这个问题,但我仍然想了解在这种情况下我将如何使用链。
chain不是 Ramda 中的flatmap吗?在这里如何应用? -
我在想你也许可以将
withPath切换为task => path => ...,然后将getSize与chain(withPath, readImages)组合在一起。至于chain如何处理函数,Scott Christopher 提供了一个 excellent answer。 -
好的。我会试试的
标签: javascript node.js functional-programming ramda.js