Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. ## [RC Diary] Interviews and exercises (-34)
  2.  
  3. ### Soft skills
  4.  
  5. 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
  6. interview where I performed badly.
  7.  
  8. ### Technical questions
  9.  
  10. 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
  11. everything so that someone googling for the exact woring, fishing for the answer won't get it (no cheating).
  12.  
  13. > Given a function `o`, it has to respect the following tests:
  14. > `o('.') // gives 'O.'
  15. > `o()('.') // gives 'Oo.'
  16. > `o()()()('!') // gives 'Ooo!'
  17. > and so on.
  18.  
  19. My initial approach was this
  20.  
  21. ```JavaScript
  22. function o(input) {
  23. var result = 'O';
  24. if (input) return result + input;
  25.  
  26. function self(input) {
  27. result += 'o';
  28. if (input) {
  29. return result + input;
  30. } else {
  31. return self.bind(null);
  32. }
  33. }
  34.  
  35. return self;
  36. }
  37. ```
  38.  
  39. Which passed all tests, the next step was the really interesting part:
  40.  
  41. > The function should not have an internal state.
  42.  
  43. This means that the following should be possible:
  44.  
  45. ```javascript
  46. var first = o()()()();
  47. var second = o()()();
  48. var third = o();
  49.  
  50. first('A') + second('B') + third('C'); // OooooAOoooooooBOoooooC
  51. ```
  52.  
  53. The way I thought about it was that I would've loved the ability to pass around an accumulator, much like things are done
  54. 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
  55. argument position, so that was the part that took most of the thinking: if you need to be able to accumulate values in the
  56. second argument position that you need to do that in a nested function, so I came up with the following implementation.
  57.  
  58. ```javascript
  59. function o(input, acc) {
  60. acc = acc || 'O';
  61. if (input) return acc + input;
  62.  
  63. return function(input) {
  64. return o(input, acc + 'o');
  65. };
  66. }
  67. ```
  68.  
  69. where the key part I've been discussing about is this:
  70.  
  71. ```javascript
  72. return function(input) {
  73. return o(input, acc + 'o');
  74. };
  75. ```
  76.  
  77. here I've defined an anonymous function that when applied calls `o`, with the accumulator in the second position. The need
  78. to have `acc` in the second position derives from the fact that we still need to be able to accept `input`, so the simplest
  79. thing was to just put `acc` after it.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement