linq.js Samples

Tutorial of Lambda Expression

    // Anonymous function
E.Range(1, 3).Select(function(value, index) { return index + ':' + value }).WriteLine();
// String like Lambda Expression (arguments => expression)
E.Range(1, 3).Select("value,index=>index+':'+value").WriteLine();

// If the number of arguments is one , you can omit argument and use id '$'
E.Range(1, 3).Select("i=>i*2").WriteLine();
E.Range(1, 3).Select("$*2").WriteLine();

// You can omit "x=>x" by using ""
E.Range(4, 7).Join(E.Range(8, 5), "x=>x", "x=>x", "outer,inner=>outer*inner").WriteLine();;
E.Range(4, 7).Join(E.Range(8, 5), "", "", "outer,inner=>outer*inner").WriteLine();
0:1
1:2
2:3
0:1
1:2
2:3
2
4
6
2
4
6
64
81
100
64
81
100

Range and Where and Select

E.Range(1, 10)
    .Where("$%3==0")
    .Select("$*10")
    .WriteLine();
30
60
90

From(Array) and Trace(for Debugging)

// use 'TraceF' output Firebug's console
var array = [213, 2, 2112, 34, 532, 65];
E.From(array).Trace("AfterFrom")
  .Where("$>100").Trace("AfterWhere")
  .WriteLine();
AfterFrom:213
AfterWhere:213
213
AfterFrom:2
AfterFrom:2112
AfterWhere:2112
2112
AfterFrom:34
AfterFrom:532
AfterWhere:532
532
AfterFrom:65

FizzBuzz (can use ForEach with index)

E.Range(1, 30)
    .Select(function(i)
    {
        return (i % 15 == 0) ? "FizzBuzz" :
               (i % 3 == 0) ? "Fizz" :
               (i % 5 == 0) ? "Buzz" :
               i;
    })
    .ForEach(function(value, index)
    {
        document.write(index + 1 + ":" + value + "<br />");
    });
1:1
2:2
3:Fizz
4:4
5:Buzz
6:Fizz
7:7
8:8
9:Fizz
10:Buzz
11:11
12:Fizz
13:13
14:14
15:FizzBuzz
16:16
17:17
18:Fizz
19:19
20:Buzz
21:Fizz
22:22
23:23
24:Fizz
25:Buzz
26:26
27:Fizz
28:28
29:29
30:FizzBuzz

From(Object) is convert to KeyValuePair / Grouping Example

var fileList = ["temp.xls", "temp2.xls", "temp.pdf", "temp.jpg", "temp2.pdf"];
var result = E.From(fileList).ToLookup("$.match(/\\.(.+$)/)[1]", "");
E.From(result).ForEach(function(kvp)
{
    document.write(kvp.Key + "::<br />");
    E.From(kvp.Value).WriteLine();
});
xls::
temp.xls
temp2.xls
pdf::
temp.pdf
temp2.pdf
jpg::
temp.jpg

From(Object) Example 2 / SelectMany / Pairwise

var data = [{ 2000: 90 }, { 2001: 85 }, { 2002: 102 }, { 2003: 78 }, { 2004: 74 }, { 2005: 89 }, { 2006: 100 }, { 2007: 94}];
var hoge = E.From(data)
    .SelectMany("E.From($)")
    .Pairwise("prev,next=>{prev:prev,next:next}")
    .Where("$.next.Value < $.prev.Value")
    .WriteLine("$.next.Key + ':' + $.next.Value");
2001:85
2003:78
2004:74
2007:94

LazyEvaluation and InfinityList

var randomSeq = E.ToInfinity().Select("Math.random()");
randomSeq.Take(10).WriteLine();
0.5100917735842267
0.4235769512514953
0.9231690184479593
0.3534544972117163
0.5727399341205792
0.6246339020453556
0.32090600443336004
0.7236100141691636
0.16323282360478086
0.2593818965005389

Using InfinityList

    var result = E.ToInfinity(1).Where("$*$*Math.PI>10000").First();
    document.write(result);
57
    var result = E.ToInfinity(1).Select("$*$*Math.PI").Where("$>10000").First();
    document.write(result);
10207.034531513238

Regular Expression Matches

var input = "abcdefgABzDefabgdg";
E.Matches(input, "ab(.)d", "i").ForEach(function(match)
{
    for (var prop in match)
    {
        document.write(prop + " : " + match[prop] + "<br />");
    }
    document.write("toString() : " + match.toString() + "<br />");
    document.write("<br />");
});
0 : abcd
1 : c
index : 0
input : abcdefgABzDefabgdg
toString() : abcd,c

0 : ABzD
1 : z
index : 7
input : abcdefgABzDefabgdg
toString() : ABzD,z

0 : abgd
1 : g
index : 13
input : abcdefgABzDefabgdg
toString() : abgd,g

Shuffle and nonparameter/nested Lambda Expression

E.Repeat(null, 10000)
    .Select("E.Range(0,10).Shuffle().First()")
    .GroupBy("", "", "key,gp=>{key:key,count:gp.Count()}")
    .OrderBy("$.key")
    .WriteLine("$.key + ':' + $.count");
0:1018
1:1047
2:1059
3:983
4:967
5:957
6:991
7:987
8:1006
9:985

OrderBy / ThenBy

var list = [
    { a: 2, b: 4, c: 1 },
    { a: 6, b: 6, c: 3 },
    { a: 2, b: 3, c: 7 },
    { a: 4, b: 4, c: 5 },
    { a: 7, b: 3, c: 2 },
    { a: 4, b: 4, c: 3 }
];
E.From(list).OrderBy("$.a").ThenByDescending("$.b").ThenBy("$.c")
    .WriteLine("$.a + ':' + $.b + ':' + $.c");
2:4:1
2:3:7
4:4:3
4:4:5
6:6:3
7:3:2

Choice - Make Dice

    var array = E.Range(1,6).ToArray();
    var Dice = function(){return E.Choice(array).First()};
    var result = Dice(); // 1 or 2 or 3 or...6
    document.write(result);
4

Choice - Make Dice 2

    var result = E.Choice(E.Range(1, 6).ToArray()).Take(3).Sum();
    document.write(result);
13

Make Alphabet

    var result = E.RangeTo('a'.charCodeAt(0), 'z'.charCodeAt(0))
      .Select("String.fromCharCode($)").ToString();
    document.write(result);
abcdefghijklmnopqrstuvwxyz

Left outer self join / Select with index

var array = [1, 2, 4, 4, 3, 3, 4, 0, 0];
var arrayWithIndex = E.From(array).Select("value, index =>  { value:value, index:index }");
arrayWithIndex.GroupJoin(arrayWithIndex, "$.index", "$.index-1", "orig,gp=>{orig:orig,gp:gp}")
    .SelectMany("$.gp.DefaultIfEmpty()", "t,alias=>{orig:t.orig,alias:alias}")
    .Where("$.alias == null || $.orig.value != $.alias.value")
    .Select("$.orig.value")
    .Write("-");
1-2-4-3-4-0

Enumerable ToJSON

var array = [null, "az", [true, 52, [62, { z: { z: "na"}}], false], { a: 43, b: null }, 10];
var json = E.From(array).ToJSON();
document.write(json);
[null,"az",[true,52,[62,{"z":{"z":"na}],false],a":43,"b":null},10]

Do and Force

var fire1 = function(){E.Repeat("ForEach:fire",3).ForEach("document.write($ + '<br/>')")};
fire1();
fire1();
var fire2 = E.Repeat("Do:fire",3).Do("document.write($ + '<br/>')");
fire2.Force();
fire2.Take(2).Force();
ForEach:fire
ForEach:fire
ForEach:fire
ForEach:fire
ForEach:fire
ForEach:fire
Do:fire
Do:fire
Do:fire
Do:fire
Do:fire

Scope of lambda expression

var number = 3;
// Can't Find number | lambda expression can use only global variable
// E.Range(1,10).Where("$ == number").WriteLine();
E.Range(1,10).Where(function(i){return i == number}).WriteLine();
3

Object Compare - use ToJSON

var seq = E.Range(1, 5).Select("{key:$<3,evenodd:$%2==0}");
seq.Distinct().Write("|","'key=' + $.key + ' ' + 'evenodd=' + $.evenodd");
seq.Distinct("$.key").Write("|","'key=' + $.key + ' ' + 'evenodd=' + $.evenodd");
seq.Distinct("$.evenodd").Write("|","'key=' + $.key + ' ' + 'evenodd=' + $.evenodd");
seq.Distinct("E.Repeat($,1).ToJSON()").Write("|","'key=' + $.key + ' ' + 'evenodd=' + $.evenodd");
key=true evenodd=false|key=true evenodd=true|key=false evenodd=false|key=false evenodd=true|key=false evenodd=false
key=true evenodd=false|key=false evenodd=false
key=true evenodd=false|key=true evenodd=true
key=true evenodd=false|key=true evenodd=true|key=false evenodd=false|key=false evenodd=true

Unfold - Fibonacci

var fib = E.Unfold({ a: 1, b: 1 }, "{a:$.b, b:$.a + $.b}").Select("$.a");
fib.Take(10).WriteLine();
1
1
2
3
5
8
13
21
34
55

Nondeterministic Programs

var apart = E.Range(1, 5);
var answers = apart
    .SelectMany(function(baker){ return apart
    .SelectMany(function(cooper){ return apart
    .SelectMany(function(fletcher){ return apart
    .SelectMany(function(miller){ return apart
    .Select(function(smith){ return {
        baker: baker, cooper: cooper, fletcher: fletcher, miller: miller, smith: smith}})})})})})
    .Where("E.From($).Distinct('$.Value').Count() == 5")
    .Where("$.baker != 5")
    .Where("$.cooper != 1")
    .Where("$.fletcher != 1 && $.fletcher != 5")
    .Where("$.miller > $.cooper")
    .Where("Math.abs($.smith - $.fletcher) != 1")
    .Where("Math.abs($.fletcher - $.cooper) != 1");

answers.SelectMany("E.From($)").WriteLine("$.Key + ':' + $.Value");
baker:3
cooper:2
fletcher:4
miller:5
smith:1

Last edited Jun 5, 2009 at 4:04 PM by neuecc, version 8

Comments

MatthewNichols Sep 22, 2011 at 1:52 PM 
I am glad to have found this page...I have been using Linq.js for a few months but the samples here are eye opening. Thanks.