javascript - 以函数式、协变的方式使用 Array.prototype.map

标签 javascript node.js ecmascript-6 prototype-programming array.prototype.map

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.jsc.jsdirPathAbs 中。

问题:

如何以纯粹的功能性方式以及协变方式解析文件路径? (即无需讨论迭代数组的变量。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.prototypeArray.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/

相关文章:

javascript - 关于 JSLint,它对 for 循环的厌恶,以及尾调用优化

javascript - HTML 注释 <!-- 是否充当 JavaScript 中的单行注释,为什么?

JavaScript : Upload Image file and resize to different resolution then download

javascript - 如何忽略 JavaScript 中 require 的多个返回值之一?

javascript - 限制 vline 中 session 中的用户数量

javascript - AngularJS 在刷新之前不会更新 View ?

javascript - Puppeteer - ProtocolError : Protocol error (Page. printToPDF):打印不可用

javascript - 找不到模块 express——在 Windows 上

javascript - AngularJs 解构 $location

javascript - JS 保持日期相差1分钟