Introduction

from.js is a powerful, high-speed LINQ implementation for JavaScript.

Basic Usage


<html>
    <head>
        <script src="from.js"></script>
    </head>
    <body>
        <script>
            var numbers = [1, 2, 3];
            $from(numbers).each(function(v) {
                document.writeln(v);
            });

            // result
            // 1 2 3
        </script>
    </body>
</html>
You can access keys which will be passed by the second argument.

var data = {a: 1, b: 2, c: 3};
$from(data).each(function(v, k) {
    document.writeln(k + ":" + v);
});

// result
// a:1 b:2 c:3
You can stop iterating by returning false.

var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
var broken = $from(numbers).each(function(v) {
    document.writeln(v);
    return v != 6;
}).broken;

// 1 2 3 4 5 6

document.writeln("The loop was" + (broken ? "" : " not") + " broken.");

// The loop was broken.

Lambda Expressions

You can use Lambda Expressions instead of Functional Expressions like this:

var numbers = [1, 2, 3];

$from(numbers).each(function(v) {
    alert(v);
});

// or

$from(numbers).each("v => alert(v)");
You can omit argument list when using lambda expressions. In this case, #n will refer to the n-th parameter.

$from(numbers).each("alert(#0)");
There are also other special directors. $ means the first parameter, $$ means the second parameter, and @ means the last parameter.

$from(numbers).each("alert($)");
These directors are very useful in that most LINQ functions in this library pass value by the first parameter, key by the second parameter, and external argument by the last parameter.

External Arguments


var vipList = ["Smith", "Johnson", "Williams"];

var name = prompt("Enter your name");
var nameCount = $from(vipList).count(function(vipName) {
    return vipName == name;
});

if (nameCount == 0) {
    alert("You are not a vip");
}
else {
    alert("You are our vip");
}
The function which was passed for the predicate is using a closure, name. Would it be possible to change this functional expression to a lambda expession? Because from.js supports lambda expressions through strings, closures cannot be accessed in this case. To enable this, from.js provides external argument to callback functions, which will be passed by the last parameter. (the 3rd parameter in this example)

var nameCount = $from(vipList).count("(vipName, index, arg) => vipName == arg", name);

// or just

var nameCount = $from(vipList).count("$ == @", name);

Abbreviated forms of special directors

$property is same as $.property, and $0 is same as $[0]. These rules are also applied to $$, @.

var people = [
    {name: "Smith", sex: "male"},
    {name: "Johnson", sex: "male"},
    {name: "Williams", sex: "gay"}
];

// finding Johnson, male
$from(people)
    .where("$name == @0 && $sex == @1", ["Johnson", "male"])
    .each("document.writeln('found on ' + $$)");

Last edited Jun 6, 2012 at 5:20 AM by suckgamoni, version 5

Comments

No comments yet.