CoffeeScript - Comprehensions



In the previous chapter, we have learnt various loops provided by CoffeeScript, while and its variants. In addition to those, CoffeeScript provides additional loop structures known as comprehensions.

These comprehensions replace the for loop in other programming languages, if we add the optional guard clauses and the value of the current array index explicitly. Using comprehensions, we can iterate arrays as well as objects and the comprehensions that iterate arrays are expressions, and we can return them in a function or assign to a variable.

S.No. Statement & Description
1 for..in comprehensions

The for..in comprehension is the basic form of comprehension in CoffeeScript using this we can iterate the elements of a list or array.

2 for..of comprehensions

Just like Arrays CoffeeScriptScript provides a containers to store key-value pairs known as objects. We can iterate objects using the for..of comprehensions provided by CoffeeScript.

3 list comprehensions

The list comprehensions in CoffeeScript are used to map an array of objects to another array.

Index of comprehensions

The list/array of elements have an index which can be used in comprehensions. You can use it in comprehensions using a variable as shown below.

for student,i in [element1, element2, element3]

Example

The following example demonstrates the usage of index of the for…in comprehension in CoffeeScript. Save this code in a file with name for_in_index.coffee

for student,i in ['Ram', 'Mohammed', 'John']
   console.log "The name of the student with id "+i+" is: "+student 

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c for_in_index.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var i, j, len, ref, student;

  ref = ['Ram', 'Mohammed', 'John'];
  for (i = j = 0, len = ref.length; j < len; i = ++j) {
    student = ref[i];
    console.log("The name of the student with id " + i + " is: " + student);
  }
}).call(this);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee for_in_index.coffee

On executing, the CoffeeScript file produces the following output.

The name of the student with id 0 is: Ram
The name of the student with id 1 is: Mohammed
The name of the student with id 2 is: John 

Postfix form of comprehensions

Just like postfix if and unless, CoffeeScript provides the postfix form of the Comprehensions which comes handy while writing the code. Using this, we can write the for..in comprehension in a single line as shown below.

#Postfix for..in comprehension
console.log student for student in ['Ram', 'Mohammed', 'John']

#postfix for..of comprehension
console.log key+"::"+value for key,value of { name: "Mohammed", age: 24, phone: 9848022338}
show example

Assigning to a variable

The comprehension we use to iterate arrays can be assigned to a variable and also returned by a function.

Example

Consider the example given below. Here you can observe that we have retrieved the elements of an array using for..in comprehension and assigned this to a variable named names. And we also have a function which returns a comprehension explicitly using the return keyword. Save this code in a file with name example.coffee

my_function =->
   student = ['Ram', 'Mohammed', 'John']
   
   #Assigning comprehension to a variable
   names = (x for x in student )
   console.log "The contents of the variable names are ::"+names
   
   #Returning the comprehension
   return x for x in student
console.log "The value returned by the function is "+my_function() 

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c example.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var my_function;

  my_function = function() {
    var i, len, names, student, x;
    student = ['Ram', 'Mohammed', 'John'];
    names = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = student.length; i < len; i++) {
        x = student[i];
        results.push(x);
      }
      return results;
    })();
    console.log("The contents of the variable names are ::" + names);
    for (i = 0, len = student.length; i < len; i++) {
      x = student[i];
      return x;
    }
  };

  console.log("The value returned by the function is " + my_function());

}).call(this);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee example.coffee

On executing, the CoffeeScript file produces the following output.

The contents of the variable names are ::Ram,Mohammed,John
The value returned by the function is Ram 

The by keyword

CoffeeScript provides ranges to define a list of elements. For example, the range [1..10] is equivalent to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] where, every element is incremented by 1. We can also change this increment using the by keyword of comprehensions.

Example

The following example demonstrates the usage of the by keyword of the for..in comprehension provided by CoffeeScript. Save this code in a file with name by_keyword_example.coffee

array = (num for num in [1..10] by 2)
console.log array

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c by_keyword_example.coffee

On compiling, it gives you the following JavaScript.

// Generated by CoffeeScript 1.10.0
(function() {
  var array, num;

  array = (function() {
    var i, results;
    results = [];
    for (num = i = 1; i <= 10; num = i += 2) {
      results.push(num);
    }
    return results;
  })();

  console.log(array);

}).call(this);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee by_keyword_example.coffee

On executing, the CoffeeScript file produces the following output.

[ 1, 3, 5, 7, 9 ] 
Advertisements