Recently I got test task at the project, it is fairly simple:
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
And my solution was:
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;
};
And I got the reply that tech lead didn't like my solution at all and I'm not hired to the project. I'm really confused, do you have any idea what else he could expect? Do you see here any alternative solutions?