A little JavaScript problem

  • Published: 2016-11-25
  • Modified: 2016-11-26 01:57
  • By: Mishoo
  • Tags: lisp, javascript, lambda
  • Comments: 0 (closed)
Nov
25
2016

A little JavaScript problem

In fact, this isn't about JavaScript, but that's the context I've discussed it in. I encourage you to think about it in more programming languages. (are there languages in which this can't be done?)

The problem: define functions range, map, reverse and foreach, obeying the restrictions below, such that the following program works properly. It prints the squares of numbers from 1 to 10, in reverse order.

var numbers = range(1, 10);
numbers = map(numbers, function (n) { return n * n });
numbers = reverse(numbers);
foreach(numbers, console.log);

/* output:

   100
   81
   64
   49
   36
   25
   16
   9
   4
   1
*/

Restrictions

Feel free to define utilities; you don't have to restrict your program to these 4 functions. It does not matter how fast, small or elegant it is — if you can do it within the limitations above, I think you're an above-average programmer and I would probably hire you. (however: I'm not hiring)

Just for reference, my implementation (in ES6) is 8 lines of code, and it isn't totally unreadable. :-)

PS: please don't post your solutions, or links, here. I will not publish them. But feel free to email me in private if you really want me to look into it.