Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. const _ = require('underscore');
  2.  
  3. // Challenge:
  4. //
  5. // Write a function that accepts as argument a "function of one variable", and returns a new
  6. // function. The returned function should invoke the original parameter function on every "odd"
  7. // invocation, returning undefined on even invocations.
  8. //
  9. // Test case:
  10. // function to wrap via alternate(): doubleIt, which takes a number and returns twice the input.
  11. // input to returned function: 1,2,3,4,9,9,9,10,10,10
  12. // expected output: 2, undefined, 6, undefined, 18, undefined, 18, undefined, 20, undefined
  13.  
  14. const input = [1,2,3,4,9,9,9,10,10,10];
  15. const doubleIt = x => x * 2;
  16.  
  17. const alternate = (fn) => {
  18. // Implement me!
  19. //
  20. // The returned function should only invoke fn on every
  21. // other invocation, returning undefined the other times.
  22. }
  23.  
  24. var wrapped = alternate(doubleIt)
  25.  
  26. _.forEach(input, (x) => console.log(wrapped(x)))
  27. // expected output: 2, undefined, 6, undefined, 18, undefined, 18, undefined, 20, undefined
  28.  
  29. const alternate = (fn) => {
  30. let odd = false;
  31.  
  32. return (x) => {
  33. odd = !odd;
  34.  
  35. if (odd) {
  36. return fn(x);
  37. }
  38.  
  39. return undefined;
  40. };
  41. };
  42.  
  43. // An alternate solution if ternary operator (?) is allowed according to coding standards used on the project.
  44. // Sometimes it's treated as bad practise.
  45. const alternateShort = (fn) => {
  46. let odd = false;
  47.  
  48. return (x) => (odd = !odd) ? fn(x) : undefined;
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement