Matthew Harwood Matthew Harwood - 11 days ago 4
Javascript Question

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

I think this technique is called currying.

Problem:

https://repl.it/E4iG

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


Question:
How do I use
hasType
so in the end I can replace the un-named anon function to
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.
});

Answer

hasType is referencing a "type" variable that doesn't exist in its scope. You'll need to inline that function for it to pick up type (or wrap it in a closure, but that's pretty much the same thing)

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


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

P.S. - unrelated, but in ES6, "{type: type}" can be shortened to "{ type }"

Comments