我正在使用ramda
和data.task
编写一个小型实用程序,它可以从目录中读取图像文件并输出它们的大小。我得到它的工作就像这样:如何用Ramda.js重构这个组合函数?
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中的目录名通过两次:一次读取文件和第二阅读路径的时间。这意味着我必须调用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'](http://ramdajs.com/docs/#chain)如何处理函数:'chain(f,g)(x)=> f(g(x),x)'。 –
嘿@ScottSauyet - 希望得到你的关注。我解决了这个问题,但我仍然想了解在这种情况下我将如何使用链。拉姆达中的“链”不仅仅是“平面图”吗? 这将如何适用? –
我在想你可能可以将'withPath'切换到'task => path => ...',然后用'chain(withPath,readImages)'编写'getSize'。至于“链”如何在函数上工作,斯科特·克里斯托弗提供了一个[优秀的答案](https://stackoverflow.com/a/45787799/1243641)。 –