编写一个满足以下测试的函数 f

2023-12-11

我有一个问题一直困扰着我,需要帮助解决。

下面是一个需要解决的测试。我已经成功地整合了一个解决方案,该解决方案适用于 85% 的覆盖范围,但它是我坚持的最后 15%。

describe("f", function() {
  it("should work", function() {
    expect(f("l")).toEqual("fl");
    expect(f()("l")).toEqual("fol");
    expect(f()()("l")).toEqual("fool");
    expect(f()()("t")).toEqual("foot");
    expect(f()()()()()("l")).toEqual("foooool");
    // And so on such that the number of calls continues
    // to increase the number of letter "o" in the string 
    // until the function is called with a string.

    // BONUS: also the function should be stateless:
    var a = f()();
    expect(a("A")).toEqual("fooA");
    expect(a()()()("B")).toEqual("foooooB");
    expect(a()("C")).toEqual("foooC");
  });
});

解决方案:

function f(input) {  
  let result = 'f'
  let cf = (c) => {
    if (c) {
      return result + c
    }
    result += 'o'

    return cf
  }

  return cf(input)
}

这适用于除最后一个奖励测试之外的所有测试。


你必须创建一个新的f()每当调用返回的函数时实例:

 const f = (char, prev = "f") => char ? (prev + char) : (char2 => f(char2, prev + "o"));

如果隐藏的第二个参数有点作弊,这里有一个柯里化版本:

 const concat = a => b => b ? (a + b) : concat(a + "o");
 const f = concat("f");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

编写一个满足以下测试的函数 f 的相关文章

随机推荐