每个第二次函数调用?

时间:2019-07-19 08:24:55

标签: javascript closures

最近我在该项目上得到了测试任务,这很简单:

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;
};

我得到的答复是,技术主管根本不喜欢我的解决方案,因此我没有被聘用到该项目中。 我真的很困惑,你知道他还能期望什么吗?

0 个答案:

没有答案