This project is read-only.

Fluent API -- chaining of methods

Most of the functions on the $linq class return a new $linq object. This makes the $linq class follow a fluent API model, that allows the chaining of $linq functions. For example:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// col = [500, 400, 300, 200, 100]
var col = $linq(arr)
    .where("x => x < 6")
    .select("x => x * 100")
    .orderByDescending("x => x")
    .toArray();
There are some $linq functions, however, that return something other than a new $linq object. These include $linq functions that return aggregate information from the $linq sequence, such as:
  • count
  • min, max, minBy, maxBy
  • any, all, contains
  • sequenceEqual, sequenceEquivalent
  • sum, average, aggregate
Some $linq functions return different representations of the sequence, such as:
  • toArray
  • toDicationary
  • toDelimitedString
  • toJQuery
And, finally, one $linq function (namely, the 'foreach' function) returns nothing--instead, iterating across the sequence.

Non-mutating nature

None of the functions on a $linq class inherently modify the objects they contain. Each $linq function that returns a $linq object returns an entirely new $linq object. This means that a $linq object can be reused multiple times and continually represets the same sequence of objects. For example:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var seq = $linq(arr);

// col1 = [1, 2, 3, 4, 5]
var col1 = seq.where("x => x < 6").toArray();

// col2 = [2, 4, 6, 8, 10]
var col2 = seq.where("x => x % 2 == 0").toArray();

// col3 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
var col3 = seq.select("x => x * 10").toArray();
Note that nothing stops any of the predicates, selectors, comparers, etc. passed to $linq functions from modifying the items within the $linq sequence. When the $linq constructor makes a copy of the array passed to it, it makes a shallow copy--that is, it does not make copies of the objects within the array, only of the array itself. For example:

var arr = [{id: 1, name: 'steve'},
    {id: 2, name: 'lauren'},
    {id: 3, name: 'jackson'},
    {id: 4, name: 'kate'}];
    
var seq = $linq(arr);

// Uppercase the first character
seq.foreach(function (x) { x.name[0] = x.name[0].toUpper(); });

// Append an asterisk while filtering out names that don't
// start with a 'K'
var temp = seq.where(function (x)
   {
      x.name = x.name + '*';

      return (x.name[0] == 'K');
   })
   .toArray();

// col = ['Steve* (1)', 'Lauren* (2)', 'Jackson* (3)', 'Kate* (4)']
var col = seq.select("x => x.name + ' (' + x.id + ')'").toArray();

// Also, at this point:
// arr = [{id: 1, name: 'Steve*'}, {id: 2, name: 'Lauren*'}, 
//        {id: 3, name: 'Jackson*'}, {id: 4, name: 'Kate*'}]

Last edited Jun 11, 2013 at 11:50 PM by battousai999, version 2