传递匿名函数时错误属性未定义(如何柯里化)?

Error property is not defined when passing an anon function (how to curry)?

我认为这种技术叫做柯里化。

问题:

https://repl.it/E4iG

ReferenceError: type is not defined
    at hasType:14:27
    at allApprovalTypes.map:18:26
    at eval:17:21
    at eval

问题: 我如何使用 hasType 所以最后我可以将未命名的 anon 函数替换为 approvals.find(hasType)?

   var approvals = [
      {type: 'media'},
      {type: 'scope'},
    ]

    var allApprovalTypes = [
      'media',
      'scope',
      'finance',
      'compliance',
    ];

   var hasType = (el) => {
       return el.type === type;
   }

   allApprovalTypes.map((type) => {
        return approvals.find((el)=> el.type === type) || {type: type} // this works.
   });

   allApprovalTypes.map((type) => {
      return approvals.find(hasType) || {type: type} // this wont work.        
   });

hasType 引用的 "type" 变量在其范围内不存在。您需要内联该函数以获取类型(或将其包装在闭包中,但这几乎是一回事)

allApprovalTypes.map((type) => {
  return approvals.find((el) => {
       return el.type === type;
   }) || {type: type}
});


   // closure
   var hasType = (type) => (el) => {
       return el.type === type;
   }

P.S。 - 无关,但在 ES6 中,“{type: type}”可以缩写为“{ type }”

您可以使用 .bind()。您可以将 type(额外参数)传递给回调。

var approvals = [
      {type: 'media'},
      {type: 'scope'},
    ]

    var allApprovalTypes = [
      'media',
      'scope',
      'finance',
      'compliance',
    ];

   var hasType = (el, type) => {
       return el.type === type;
   }

   console.log(allApprovalTypes.map((type) => {
        return approvals.find(hasType.bind(null, type)) || {type: type} // this works.
   }));

   

   //without bind();
   console.log(allApprovalTypes.map((type) => {
        return approvals.find((el) => return hasType(el, type)) || {type: type} // this works.
   }));