Writing a function f which would satisfy the following test

I have a question which I'm stuck on and need help solving.

Below is a test which needs to be solved. I've managed to put together a solution which works for 85% of the coverage but its the last 15% I'm stuck on.

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

The solution:

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

    return cf
  }

  return cf(input)
}

which works for all but the last bonus test.

Answers:

Answer

You have to create a new f() instance whenever the returned function is called:

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

If that hidden second param is a bit to cheaty here is a curried version:

 const concat = a => b => b ? (a + b) : concat(a + "o");
 const f = concat("f");

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.