1

I'm trying to convert the following JS text book example into Livescript:

   function cf(){
       var result = new Array();
       for (var i=0; i < 10; i++) {
         result[i] = function(num){
           return function(){
             return num;
           };
          }(i);
       }
       return result;
    }
    console.log( cf()[2]() );

My attempt is this:

cf = ->
  res=[]
  for i in [ 0 til 10 ]
    f = (num) ->
      ->
        num
    res[i] = f(i)
  res

console.log cf! . [3]!

However, lsc balked at the last line.

I tried http://js2ls.org/public/ which provides this Livescript output (from the first javascript fragment):

cf = ->
  result = new Array
  i = 0
  while i < 10
    result[i] = (num) -> -> num
    i
    i++
  result

console.log cf!.2!

which is not correct.

How should the javascript fragment be coded in Livescript?

user1860288
  • 512
  • 2
  • 6
  • 18

2 Answers2

1
cf = -> [0 to 9] |> map (i) -> -> i
cf!.2!

Using prelude-ls map

homam
  • 1,945
  • 1
  • 19
  • 26
0

Actually either console.log cf!.2! or console.log cf![2]! would have worked in my code.

I don't like the use of named function. Is there a better way?

Also, it is curious that js2ls seems to stumble on the conversion.

user1860288
  • 512
  • 2
  • 6
  • 18