I've done quite a few interviews today. One of which I don't think went that well, strangely enough it was the first informal interview where I performed badly.
I've got a few questions but the most interesting was the one that I'm about to present, I've changed the wording and everything so that someone googling for the exact woring, fishing for the answer won't get it (no cheating).
Given a function
o
, it has to respect the following tests:o('.') // gives 'O.'
o()('.') // gives 'Oo.'
o()()()('!') // gives 'Ooo!'
and so on.
My initial approach was this
function o(input) {
var result = 'O';
if (input) return result + input;
function self(input) {
result += 'o';
if (input) {
return result + input;
} else {
return self.bind(null);
}
}
return self;
}
Which passed all tests, the next step was the really interesting part:
The function should not have an internal state.
This means that the following should be possible:
var first = o()()()();
var second = o()()();
var third = o();
first('A') + second('B') + third('C'); // OooooAOoooooooBOoooooC
The way I thought about it was that I would've loved the ability to pass around an accumulator, much like things are done
when fold
ing over a list to sum its values, the tricky bit in this case is the fact that the accumulator is in the second
argument position, so that was the part that took most of the thinking: if you need to be able to accumulate values in the
second argument position that you need to do that in a nested function, so I came up with the following implementation.
function o(input, acc) {
acc = acc || 'O';
if (input) return acc + input;
return function(input) {
return o(input, acc + 'o');
};
}
where the key part I've been discussing about is this:
return function(input) {
return o(input, acc + 'o');
};
here I've defined an anonymous function that when applied calls o
, with the accumulator in the second position. The need
to have acc
in the second position derives from the fact that we still need to be able to accept input
, so the simplest
thing was to just put acc
after it.