0

I am reading about the 30s of code in JavaScript and find the following code in adapter chapter. I did not quite understand how this code snippets bind the map and the callback function to the context. Could someone help in explaining this?

 const call = (key, ...args) => (context) => context[key](...args);
 Promise.resolve([1, 2, 3])
 .then(call('map', x => 2 * x)) 
 //Does it mean [1,2,3][map](x=> 2*x)? How does this work?
 .then(console.log); 
 // [ 2, 4, 6 ]
Osito Wang
  • 29
  • 2
  • it's not entirely clear whether you're asking about what the `=>` means (arrow functions, see [this question's answers](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript)) or how it is that the function that `call` returns has access to `key` and `args` (because the returned function *closes over* `key` and `args`, see [this question's answers](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work)). I thought the latter, but others thought the former, so... – T.J. Crowder Nov 26 '18 at 19:03
  • 1
    @georg, why reopen this? @ Osito - If once you've reviewed the various answers to the various questions on the list of duplicate targets you still don't understand this code, post a new question making clear what specifically it is that you don't understand (e.g., not arrow functions or closures or whatever because those are covered by the linked questions). Happy coding! – T.J. Crowder Nov 26 '18 at 19:04
  • `const call = (key, ...args) => (context) => context[key](...args);` -- that returns a function used as a promise, maybe replace `context` with `result`, as more standard in a Promise chain. – user2864740 Nov 26 '18 at 19:04
  • Hmm, your question title and question body seem to be asking about quite different parts of the code in the question. The more I reread it, the less I understand what the question is asking about. – Quentin Nov 26 '18 at 19:08
  • It means what you describe in the comment. The array is passed to the callback in the 'then' – Jonathan Nov 26 '18 at 19:09
  • thanks. Guys. I think the main reason I did not understand the code is because I did not notice that array["map] equals to array.map(). Thank you all. – Osito Wang Nov 26 '18 at 20:15

0 Answers0