我正在使用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)。 –