Skip to content
Jing Lu edited this page May 25, 2013 · 8 revisions

A function with a default return is lambda expression in ReoScript.

Define Lambda

var plus = (a, b) => a + b;

It is same as below:

function plus(a, b) {
  return a + b;
}

Using Lambda same as function calling:

var result = plus(1, 2);

The result is:

3

Array Extension with Lambda support

Here is a function named 'where' which find matched element over an array by given predicate lambda expression.

Array.prototype.where = predicate => {
  var result = [];
    
  for(var element in this)
    if(predicate(element))
      result.push(element);

  return result;
};

Now use 'where' to find numbers that is greater than 10:

var arr = [1, 2, 5, 7, 8, 10, 12, 15, 17, 18, 19];
var result = arr.where(n => n > 10);

The result is:

[12, 15, 17, 18, 19]

If element in array is of object type, a selector lambda used to return which property to be used. e.g.:

Array.prototype.sum = selector => {
  var total = 0;
    
  for(element in this) {
    total += (selector == null ? element : selector(element));
  }

  return total;
};

Lambda selector returns property from an object:

function Sales(year, amount) {
  this.year = year;
  this.amount = amount;
}
  
var arr = [ new Sales(2005, 130),
            new Sales(2006, 100),
            new Sales(2007, 210),
            new Sales(2008, 190), ];

var result = arr.sum(obj => obj.amount);

The result is:

630

Standard Array Extension

Now there is a set of method called Standard Array Extension Library is available since ReoScript v1.2. You can find the source script in source code:

scripts/array.rs