Say I have the following input (to be used with
Node
, but the problem is more general, and not Node related):
- Absolute path to a directory, call it
dirPathAbs
- An array of basenames (call it
namesSeq
) of some JS files that exist inside that folder
例如:
我可能有 namesSeq = ['a', 'b', 'c']
对应于一些 a.js
, b.js
,c.js
在 dirPathAbs
中。
问题:
如何以纯粹的功能性方式以及协变方式解析文件路径? (即无需讨论迭代数组的变量。Covariant 可能不是这个词,抱歉)。 p>
我不想要的:
namesSeq.map(base => path.join(dirPathAbs, `${base}.js`));
也不是
namesSeq.map(base => require.resolve(path.join(dirPathAbs, base)));
也不是
namesSeq.map(base => path.resolve.bind(dirPathAbs)(base));
也不是
const cb = base => path.resolve.bind(dirPathAbs)(base);
namesSeq.map(cb);
我期待这个能工作
namesSeq.map(path.resolve.bind(dirPathAbs))
但事实并非如此。我认为 path.resolve.bind(dirPathAbs)
接收作为输入 namesSeq
,这是提供给 Array.prototype.map
的回调的第三个参数>,因为我看到的错误是
TypeError: Path must be a string. Received [ 'a', 'b', 'c' ]
这只是让我感到沮丧的此类练习中的一个,但是自从学习 JS 以来,一整类类似的练习都让我头疼。关于 this
如何绑定(bind),以及如何使用所有这些 Function.prototype
、Array.prototype
和 friend ,我仍然遗漏了一些东西.
最佳答案
你可以在中间添加另一个函数来吃掉那些额外的变量:
const take = (fn, n) => (...args) => fn(...args.slice(0, n));
const bind = fn => (...args) => (...args2) => fn(...args, ...args2);
namesSeq.map(take(bind(path.resolve)(dirPathAbs), 1));
但我没有看到命名参数有任何优势。
关于javascript - 以函数式、协变的方式使用 Array.prototype.map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54057185/