javascript-以函数,协变方式使用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’],它对应于dirPathAbs中的一些a.js,b.js,c.js.

问题:

如何以纯粹的功能方式以及协变方式解析文件的路径? (即无需谈论迭代数组的变量.抱歉,协变量可能不是这个词).

我不想要的:

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以来,一整类类似的练习让我头疼.关于绑定方式以及所有这些Function.prototype,Array.prototype&朋友应该使用.

最佳答案
您可以在中间添加一个函数来消耗这些额外的变量:

 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));

但我看不到命名参数的任何优势.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...