Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const _ = require('underscore');
- // Challenge:
- //
- // Write a function that accepts as argument a "function of one variable", and returns a new
- // function. The returned function should invoke the original parameter function on every "odd"
- // invocation, returning undefined on even invocations.
- //
- // Test case:
- // function to wrap via alternate(): doubleIt, which takes a number and returns twice the input.
- // input to returned function: 1,2,3,4,9,9,9,10,10,10
- // expected output: 2, undefined, 6, undefined, 18, undefined, 18, undefined, 20, undefined
- const input = [1,2,3,4,9,9,9,10,10,10];
- const doubleIt = x => x * 2;
- const alternate = (fn) => {
- // Implement me!
- //
- // The returned function should only invoke fn on every
- // other invocation, returning undefined the other times.
- }
- var wrapped = alternate(doubleIt)
- _.forEach(input, (x) => console.log(wrapped(x)))
- // expected output: 2, undefined, 6, undefined, 18, undefined, 18, undefined, 20, undefined
- const alternate = (fn) => {
- let odd = false;
- return (x) => {
- odd = !odd;
- if (odd) {
- return fn(x);
- }
- return undefined;
- };
- };
- // An alternate solution if ternary operator (?) is allowed according to coding standards used on the project.
- // Sometimes it's treated as bad practise.
- const alternateShort = (fn) => {
- let odd = false;
- return (x) => (odd = !odd) ? fn(x) : undefined;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement