Advertisement
Guest User

Untitled

a guest
May 3rd, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. // a "generic" function doing some work for us (in this case, just multiply
  2. // value with a factor `n`)
  3. function times(value, n) {
  4. return value * n;
  5. }
  6.  
  7. // "higher order function" to generate more specific functions
  8. function makeTimes(n) {
  9. return function(value) {
  10. return times(value, n);
  11. }
  12. }
  13.  
  14. // using the specific functions (just to demonstrate, all good)
  15. const times3 = makeTimes(3);
  16. const times7 = makeTimes(7);
  17. console.log(times3(3), times7(3));
  18.  
  19. // we may want to do things "in bulk", i.e. generate multiple higher order
  20. // functions "in one go"
  21. // This first attempt is broken, why?
  22. function makeTimesMultipleBroken(arrayOfNs) {
  23. const result = [];
  24. for (var i = 0; i < arrayOfNs.length; i++) {
  25. result.push(function(value) {
  26. return times(value, arrayOfNs[i]);
  27. });
  28. }
  29. return result;
  30. }
  31.  
  32. var someTimes = makeTimesMultipleBroken([ 4, 5 ]);
  33. var times4 = someTimes[0], times5 = someTimes[1];
  34. console.log(times4(3), times5(3));
  35.  
  36. // This second attempt works. Why?
  37. function makeTimesMultiple(arrayOfNs) {
  38. return arrayOfNs.map(function(n) {
  39. return function(value) {
  40. return times(value, n);
  41. }
  42. });
  43. }
  44.  
  45. someTimes = makeTimesMultiple([ 4, 5 ]);
  46. times4 = someTimes[0];
  47. times5 = someTimes[1];
  48. console.log(times4(3), times5(3));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement