Easier to read lambdas

Igor Bukanov igor at mir2.org
Tue May 29 07:18:06 PDT 2007


Hi!

Consider the following es3 examples involving simple and more complex lamdas:

array.sort(function(a, b) { return a - b; });

array.sort(function(a, b) {
    if (typeof a != "number" || typeof b != "number")
        throw "Unexpected type of array element";
    return a - b;
});

setTimeout(function() {
   if (someCondition)
       reportTimeout();
}, 1000);

This not only looks ugly due to that }); but IMO hard to read since it
is not immediately obvious where the lambda parameter ends especially
in the third example.

In es4 the first one can be written using function shortcut as:

array.sort(function(a, b) a - b);

But such shorter form is not available for multi-statement lambdas so
the second and third examples will continue to look ugly and be hard
to read (again IMO).

To mitigate this I suggest to allow to move the definition of the body
of lambda used inside an expression statement to the end of the
statement. This would make possible to write:

array.sort(function(a, b)) a - b;

array.sort(function(a, b)) {
    if (typeof a != "number" || typeof b != "number")
        throw "Unexpected type of array element";
    return a - b;
}

setTimeout(function(), 1000) {
   if (someCondition)
       reportTimeout();
}

Here is more examples:

Upper-case the array:

var upper = array.map(function(elem)) elem.toUpperCase();

Do complex SQL transaction:

function doSomethingWithNewPeople() {
   let selectSQL ="SELECT code, name from people where status='new'";
   let insertSQL = "INSERT INTO young(name,age) values (?,?)";
   connection.transaction(function(tx)) {
       connection.prepare(function(selectStatement), selectSQL) {
           connection.prepare(function(insertStatement), insertSQL) {
               selectStatement.executeQuery(function(name, age)) {
                   if (name.match(/.*Joe/) && age % 2)
                       insertStatement.execute(name, age);
               }
           }
       }
   }
}

In fact such notation competes with using generators for enumeratons. Compare:

for (let [index, elem] in array)
    print("["+index+"]="+elem);

with

array.forEach(function(elem, index))
    print("["+index+"]="+elem);

So how does it look for you?

Regards, Igor



More information about the Es4-discuss mailing list