SlideShare uma empresa Scribd logo
1 de 65
Baixar para ler offline
JavaScript
“      ”
       - 2011.7
•       /       / Jeffrey Zhao /

•
•         http://blog.zhaojie.me/

•         @

• F#, JavaScript, Scala, C#, Python, .NET, Mono...
• Java
Javascript Uncommon Programming
Javascript Uncommon Programming
// C#
List<string> keywords = ...;
var result = keywords
    .GroupBy(k => k[0].ToUpper())
    .ToDictionary(
        g => g.Key,
        g => g.OrderBy(k => k).ToList());




// F#
let keywords = ...
let result =
    keywords
    |> Seq.groupBy (fun k -> k.[0].ToUpper())
    |> Seq.map (fun (k, v) -> (k, v |> Seq.sort))
    |> Map.ofSeq
# Ruby
keywords = ...
result = keywords 
    .group_by { |k| k[0,1].upcase } 
    .each { |key, value| value.sort! }




// JavaScript
var keywords = ...;
var result = keywords
    .groupBy(function (k) { return k[0].toUpperCase(); })
    .each(function (key, value) { value.sort(); });
Java
List<String> keywords = ...;
Map<Character, List<String>> result = new HashMap<...>();

for (String k: keywords) {
    char firstChar = k.charAt(0);

    if (!result.containsKey(firstChar)) {
        result.put(firstChar, new ArrayList<String>());
    }

    result.get(firstChar).add(k);
}

for (List<String> list: result.values()) {
    Collections.sort(list);
}
*
Map<Character, List<String>> result = keyword
  .groupBy(
    new F<String, Character> {
       public Character f(String s) { return s.charAt(0); }
    })
  .toMap(
    new F<Grouping<Character, String, Character> {
       public Charactor f(Grouping<Char, String> g) {
         return g.getKey();
       }
    },
    new F<Grouping<Character, String>, List<String>> {
       public List<String> f(Grouping<Character, String> g) {
         return g
           .orderBy(
             new F<String, String> {
                public String f(String s) { return s; }
             })
           .toList();
       }
    });

                                                                *   C# API
•
•
•
Java

•
•
•
•
•
•   Lambda

•
•
Javascript Uncommon Programming
JavaScript
•
•
• prototype
• this
• apply call   arguments constructor
  callee
JavaScript Ninja
Javascript Uncommon Programming
1
var fib = function () {
    var state = 0, last0, last1;

    return {
        moveNext: function () {
             if (state == 0) { //
                 this.current = 0;
                 state = 1;
             } else if (state == 1) { //
                 this.current = 1;               var iter = fib();
                 last1 = 0;                      while (iter.moveNext()) {
                 state = 2;                          print(iter.current);
             } else {                            }
                 last0 = last1;
                 last1 = this.current;
                 this.current = last0 + last1;
             }

            return true;
        }
    }
}
JavaScript 1.7*
function fibonacci() {
    yield 0;
    yield 1;

    var a = 0, current = 1;
    while (true) {                           for (var i in fibonacci()) {
        var b = a;                               print(i);
        a = current;                         }
        current = a + b;

        yield current;
    }
}




               * Firefox 2.0+ only: https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators
2
var compare = function (x, y) {
    return x - y;
}

var swap = function (a, i, j) {
    var t = a[i]; a[i] = a[j]; a[j] = t;
}

var bubbleSort = function (array) {
    for (var x = 0; x < array.length; x++) {
        for (var y = 0; y < array.length - x; y++) {
            if (compare(array[y], array[y + 1]) > 0) {
                swap(array, y, y + 1);
            }
        }
    }
}
var compare = function (x, y, callback) {         var innerLoop = function (array, x, y, callback) {
    setTimeout(10, function () {                      if (y < array.length - x) {
        callback(x - y);                                  compare(array[y], array[y + 1], function (r) {
    });                                                        if (r > 0) {
}                                                                  swap(array, y, y + 1, function () {
                                                                        innerLoop(array, x, y + 1, callback);
var swap = function (a, i, j, callback) {                          });
    var t = a[i]; a[i] = a[j]; a[j] = t;                       } else {
    repaint(a);                                                    innerLoop(array, x, y + 1, callback);
                                                               }
    setTimeout(20, callback);                             });
}                                                     } else {
                                                          callback();
var outerLoop = function (array, x, callback) {       }
    if (x < array) {                              }
        innerLoop(array, x, 0, function () {
             outerLoop(array, x + 1, callback);   outerLoop(array, 0, function () {
        });                                           console.log("done!");
    } else {                                      });
        callback();
    }
}
var compare = function (x, y, callback) {         var innerLoop = function (array, x, y, callback) {
    setTimeout(10, function () {                      if (y < array.length - x) {
        callback(x - y);                                  compare(array[y], array[y + 1], function (r) {
    });                                                        if (r > 0) {
}                                                                  swap(array, y, y + 1, function () {
                                                                        innerLoop(array, x, y + 1, callback);
var swap = function (a, i, j, callback) {                          });
    var t = a[i]; a[i] = a[j]; a[j] = t;                       } else {




                            D
    repaint(a);                                                    innerLoop(array, x, y + 1, callback);
                                                               }




                           M
    setTimeout(20, callback);                             });
}                                                     } else {



                         T
                                                          callback();
var outerLoop = function (array, x, callback) {       }
    if (x < array) {                              }
        innerLoop(array, x, 0, function () {
             outerLoop(array, x + 1, callback);   outerLoop(array, 0, function () {
        });                                           console.log("done!");
    } else {                                      });
        callback();
    }
}
*

•   JavaScript          DSL

•                toString

•     eval




                              *   JavaScript ECMAScript 3
toString
var f = function () {
          ...
      }




var f = eval(compile(function () {
     ...
}));
var compile = function (f) {

    //
    var code = f.toString();

    //
    var ast = parse(code);

    //
    return generateCode(ast);
}
•                JS   • eval           “
                            ”
•                     •
•                         JavaScript
    JavaScript
eval
• eval
• eval   compile

•
 •       eval   compile
 •
 •         ECMAScript 5    Strict Mode
Jscex
Jscex

• JavaScript Computation EXpression
• JavaScript
• F#                      JavaScript
 •     “            ”
 •     JavaScript       JavaScript
Jscex

•
    •   Jscex              JavaScript

•
    •   Jscex                           /

• JavaScript           /
    •           ECMAScript 3
Javascript Uncommon Programming
•
    •
    •
•
    •
    •
var compareAsync = eval(Jscex.compile("async", function (x, y) {
     $await(Jscex.Async.sleep(10)); // each "compare" takes 10 ms.
     return x - y;
}));

var swapAsync = eval(Jscex.compile("async", function (a, i, j) {
     var t = a[i]; a[i] = a[j]; a[j] = t; // swap
     repaint(a); // repaint after each swap
     $await(Jscex.Async.sleep(20)); // each "swap" takes 20 ms.
}));

var bubbleSortAsync = eval(Jscex.compile("async", function (array) {
     for (var x = 0; x < array.length; x++) {
         for (var y = 0; y < array.length - x; y++) {
             var r = $await(compareAsync(array[y], array[y + 1]));
             if (r > 0) $await(swapAsync(array, y, y + 1));
         }
     }
}));

                                http://files.zhaojie.me/jscex/samples/async/sorting-animations.html?bubble
var compareAsync = eval(Jscex.compile("async", function (x, y) {
     $await(Jscex.Async.sleep(10)); // each "compare" takes 10 ms.
     return x - y;
}));

var swapAsync = eval(Jscex.compile("async", function (a, i, j) {
     var t = a[i]; a[i] = a[j]; a[j] = t; // swap
     repaint(a); // repaint after each swap
     $await(Jscex.Async.sleep(20)); // each "swap" takes 20 ms.
}));

var bubbleSortAsync = eval(Jscex.compile("async", function (array) {
     for (var x = 0; x < array.length; x++) {
         for (var y = 0; y < array.length - x; y++) {
             var r = $await(compareAsync(array[y], array[y + 1]));
             if (r > 0) $await(swapAsync(array, y, y + 1));
         }
     }
}));

                                http://files.zhaojie.me/jscex/samples/async/sorting-animations.html?bubble
Jscex

//
var somethingAsync = eval(Jscex.compile("async",
    function (...) {
        //
    }
));
function () {
    var res = $await(<async work>);
}
function () {
    var res = $await(<async work>);
}

        HTTP
         UI


      Web Service
var f = eval(Jscex.compile("async", function () {
     var img = $await(readAsync("http://..."));
     console.log("loaded!");
     $await(writeAsync("./files/..."));
     console.log("saved!");
}));
…
var f = eval('(function () {
    var _b_ = Jscex.builders["async"];
    return _b_.Start(this,
        _b_.Delay(function () {
            _b_.Bind(readAsync(...), function (img) {
                console.log("loaded!");
                return _b_.Bind(writeAsync(...), function () {
                    console.log("saved!");
                    return _b_.Normal();
                });
            });
        })
    );
})');
…
var f = (function () {
    var _b_ = Jscex.builders["async"];
    return _b_.Start(this,
        _b_.Delay(function () {
            _b_.Bind(readAsync(...), function (img) {
                console.log("loaded!");
                return _b_.Bind(writeAsync(...), function () {
                    console.log("saved!");
                    return _b_.Normal();
                });
            });
        })
    );
});
Express
var app = express.createServer();

app.get('/', function (req, res) {
    /**
     *
     *
     * 1.
     * 2.
     *
     * 3.              res
     *
     *           “   ”
     **/
});

app.listen(3000);
Jscex
app.getAsync('/', eval(Jscex.compile("async", function (req, res) {

    var keys = $await(db.getKeysAsync(...));

    var results = [];
    for (var i = 0; i < keys.length; i++) {
        var r = $await(cache.getAsync(keys[i]));
        if (!r) {
            r = $await(db.getItemAsync(keys[i]));
        }

        results.push(r);
    }

    res.send(generateList(results));
})));
Jscex vs.
•
•
    •   Virtual Panel: How to Survive Asynchronous
        Programming in JavaScript

•
    •   StratifiedJS
    •   Narrative JavaScript
    •   Streamline             Jscex
Jscex vs.
•
    •
    •
    •
• Jscex
    •     JavaScript
    •
    •
Jscex vs.
•
    •
    •
    •
• Jscex
    •       JavaScript
    •       JavaScript
    •       JavaScript
Streamline

•                Jscex
    •       JavaScript
    •                    JIT
    •
•       Jscex
    •
    •   Yield – Resume vs. Asynchronous Callbacks – An
        Equivalence
Streamline (input)

var bubbleSortAsync = function (array, _) {
    for (var x = 0; x < array.length; x++) {
        for (var y = 0; y < array.length - x; y++) {
            if (compareAsync(array[y], array[y + 1], _) > 0)
                swapAsync(array, y, y + 1, _);
        }
    }
}
Streamline (compiled)
var bubbleSortAsync = function __1(array, _) {
  if (!_) {
    return __future(__1, arguments, 1);
  }                                                        if ((y < (array.length - x))) {
;                                                             return compareAsync(array[y], array[(y + 1)], __cb(_, function(__0, r) {
  var __then = _;                                               if ((r > 0)) {
  var x = 0;                                                       return swapAsync(array, y, (y + 1), __cb(_, __then));
  var __4 = false;                                              }
  return function(__break) {                                  ;
    var __loop = __nt(_, function() {                           return __then();
      var __then = __loop;                                    }));
      if (__4) {                                           }
         x++;                                                else {
      }                                                       return __break();
        else {                                             }
         __4 = true;                                     ;
      }                                                  });
    ;                                                    return __loop();
      if ((x < array.length)) {                        }(__then);
         var y = 0;                                 }
         var __3 = false;                             else {
         return function(__break) {                    return __break();
           var __loop = __nt(_, function() {        }
              var __then = __loop;                ;
              if (__3) {                          });
                 y++;                             return __loop();
              }                                 }(__then);
                else {                       };
                 __3 = true;
              }
           ;




                                                                         http://sage.github.com/streamlinejs/examples/streamlineMe.html
Jecex (input)

var bubbleSortAsync = eval(Jscex.compile("async", function (array) {
     for (var x = 0; x < array.length; x++) {
         for (var y = 0; y < array.length - x; y++) {
             var r = $await(compareAsync(array[y], array[y + 1]));
             if (r > 0)
                 $await(swapAsync(array, y, y + 1));
         }
     }
}));
Jecex (compiled)
var bubbleSortAsync = (function (array) {
    var _b_ = Jscex.builders["async"];
    return _b_.Start(this,
        _b_.Delay(function () {
            var x = 0;
            return _b_.Loop(
                function () { return x < array.length; },
                function () { x++; },
                _b_.Delay(function () {
                    var y = 0;
                    return _b_.Loop(
                        function () { return y < (array.length - x); },
                        function () { y++; }
                        _b_.Delay(function () {
                             return _b_.Bind(compareAsync(array[y], array[y + 1]), function (r) {
                                 if (r > 0) {
                                     return _b_.Bind(swapAsync(array, y, y + 1), function () {
                                          return _b_.Normal();
                                     });
                                 } else {
                                     return _b_.Normal();
                                 }
                             });
                        }),
                        false
                    );
                }),
                false
            );
        })
    );
})
Jecex (compiled)
            var bubbleSortAsync = (function (array) {
                var _b_ = Jscex.builders["async"];
                return _b_.Start(this,
                    _b_.Delay(function () {
                                                     outer loop
                        var x = 0;
                        return _b_.Loop(
                            function () { return x < array.length; },
                            function () { x++; },
                            _b_.Delay(function () {
                                var y = 0;
                                return _b_.Loop(

       inner loop                   function () { return y < (array.length - x); },
                                    function () { y++; }
                                    _b_.Delay(function () {
                                         return _b_.Bind(compareAsync(array[y], array[y + 1]), function (r) {
                                             if (r > 0) {
                                                 return _b_.Bind(swapAsync(array, y, y + 1), function () {

$await(compareAsync(...))                             return _b_.Normal();
                                                 });
                                             } else {                                $await(swapAsync(...))
                                                 return _b_.Normal();
                                             }
                                         });
                                    }),
                                    false
                                );
                            }),
                            false
                        );
                    })
                );
            })
Jscex
•
    •
    •                   “debugger”


•       JavaScript
    •   Start, Delay, Combine
    •   Loop, Try
    •   Normal, Return, Break, Continue, Throw
    •   Bind
Javascript Uncommon Programming
Node.js
... the principle we go by is, don't expect to see
a particular concurrency model put into C#
because there're many different concurrency
model ... it's more about finding things are
common to all kinds of concurrency ...

                              - Anders Hejlsberg
•
    •   JIT
    •   AOT

•
    •                      F#   Scala Python
        Twisted C# vNext
    •                           Python C#
        JavaScript 1.7
    •         …
Jscex

•
•               “   ”

•     “     ”

•
//
var fib = eval(Jscex.compile("seq", function () {
    $yield(0);
    $yield(1);

       var a = 0, current = 1;
       while (true) {
           var b = a;
           a = current;
           current = a + b;

           $yield(current);
       }
}));




                              https://github.com/JeffreyZhao/jscex/blob/master/samples/seq/fib.html
fib()
    .filter(function (n) { return n % 2 == 0; })
    .skip(2)
    .take(5)
    .zip(infinite(1))
    .map(function (a) { return a[1] + ": " + a[0]; })
    .each(print);




                          https://github.com/JeffreyZhao/jscex/blob/master/samples/seq/fib.html
var filter = eval(Jscex.compile("seq", function (iter, predicate) {
     while (iter.moveNext()) {
         if (predicate(iter.current)) {
             $yield(iter.current);
         }
     }
}));

var map = eval(Jscex.compile("seq", function (iter, mapper) {
     while (iter.moveNext()) {
         $yield(mapper(iter.current));
     }
}));

var zip = eval(Jscex.compile("seq", function (iter1, iter2) {
     while (iter1.moveNext() && iter2.moveNext()) {
         $yield([iter1.current, iter2.current]);
     }
}));

                             https://github.com/JeffreyZhao/jscex/blob/master/src/jscex.seq.powerpack.js
Maybe Monad
var maybeFunc = function () {
    var maybeA = getA();
    if (maybeA != Maybe.None) {
        var maybeB = getB();
        if (maybeB != Maybe.None) {
             return maybeA.value + maybeB.value;
        } else {
             return Maybe.None;
        }
    } else {
        return Maybe.None;
    }
}

//
var maybeFunc = eval(Jscex.compile("maybe", function () {
     var a = $try(getA());
     var b = $try(getB());
     return a + b;
}));
•       JavaScirpt DSL
    •                 +
    •   JavaScript                “   ”

•                         Jscex
    •        BSD
    •   https://github.com/JeffreyZhao/jscex
    •   http://www.sndacode.com/projects/jscex
Q &A
Javascript Uncommon Programming

Mais conteúdo relacionado

Mais procurados

Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performanceDuoyi Wu
 
Swift internals
Swift internalsSwift internals
Swift internalsJung Kim
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵Wanbok Choi
 
12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine12 Monkeys Inside JS Engine
12 Monkeys Inside JS EngineChengHui Weng
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017Wanbok Choi
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」matuura_core
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined FunctionsChristoph Bauer
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 

Mais procurados (20)

Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Swift internals
Swift internalsSwift internals
Swift internals
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」連邦の白いヤツ 「Objective-C」
連邦の白いヤツ 「Objective-C」
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined Functions
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Intro to Pig UDF
Intro to Pig UDFIntro to Pig UDF
Intro to Pig UDF
 
Learning from 6,000 projects mining specifications in the large
Learning from 6,000 projects   mining specifications in the largeLearning from 6,000 projects   mining specifications in the large
Learning from 6,000 projects mining specifications in the large
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 

Semelhante a Javascript Uncommon Programming

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changeshayato
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_onefuturespective
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Calvin Cheng
 
FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)Zach Bray
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Type script, for dummies
Type script, for dummiesType script, for dummies
Type script, for dummiessantiagoaguiar
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingSergey Shishkin
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basicswpgreenway
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 

Semelhante a Javascript Uncommon Programming (20)

TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Monadologie
MonadologieMonadologie
Monadologie
 
Scala
ScalaScala
Scala
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
 
ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changes
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Type script, for dummies
Type script, for dummiesType script, for dummies
Type script, for dummies
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional Programming
 
Ecma script 5
Ecma script 5Ecma script 5
Ecma script 5
 
Millionways
MillionwaysMillionways
Millionways
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 

Mais de jeffz

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错jeffz
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践jeffz
 
Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望jeffz
 
Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望jeffz
 
The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)jeffz
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developersjeffz
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现jeffz
 
Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程jeffz
 
Windows Phone应用开发心得
Windows Phone应用开发心得Windows Phone应用开发心得
Windows Phone应用开发心得jeffz
 
分布式版本管理
分布式版本管理分布式版本管理
分布式版本管理jeffz
 
使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架jeffz
 
针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构jeffz
 
企业开发领域的语言特性
企业开发领域的语言特性企业开发领域的语言特性
企业开发领域的语言特性jeffz
 
大话程序员可用的算法
大话程序员可用的算法大话程序员可用的算法
大话程序员可用的算法jeffz
 
面向对象与生活
面向对象与生活面向对象与生活
面向对象与生活jeffz
 
Windows内核技术介绍
Windows内核技术介绍Windows内核技术介绍
Windows内核技术介绍jeffz
 
F#语言对异步程序设计的支持
F#语言对异步程序设计的支持F#语言对异步程序设计的支持
F#语言对异步程序设计的支持jeffz
 
大众点评网的技术变迁之路
大众点评网的技术变迁之路大众点评网的技术变迁之路
大众点评网的技术变迁之路jeffz
 
Better Framework Better Life
Better Framework Better LifeBetter Framework Better Life
Better Framework Better Lifejeffz
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 

Mais de jeffz (20)

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践
 
Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望
 
Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望
 
The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developers
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现
 
Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程
 
Windows Phone应用开发心得
Windows Phone应用开发心得Windows Phone应用开发心得
Windows Phone应用开发心得
 
分布式版本管理
分布式版本管理分布式版本管理
分布式版本管理
 
使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架
 
针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构
 
企业开发领域的语言特性
企业开发领域的语言特性企业开发领域的语言特性
企业开发领域的语言特性
 
大话程序员可用的算法
大话程序员可用的算法大话程序员可用的算法
大话程序员可用的算法
 
面向对象与生活
面向对象与生活面向对象与生活
面向对象与生活
 
Windows内核技术介绍
Windows内核技术介绍Windows内核技术介绍
Windows内核技术介绍
 
F#语言对异步程序设计的支持
F#语言对异步程序设计的支持F#语言对异步程序设计的支持
F#语言对异步程序设计的支持
 
大众点评网的技术变迁之路
大众点评网的技术变迁之路大众点评网的技术变迁之路
大众点评网的技术变迁之路
 
Better Framework Better Life
Better Framework Better LifeBetter Framework Better Life
Better Framework Better Life
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 

Último

UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 

Último (20)

UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 

Javascript Uncommon Programming

  • 1. JavaScript “ ” - 2011.7
  • 2. / / Jeffrey Zhao / • • http://blog.zhaojie.me/ • @ • F#, JavaScript, Scala, C#, Python, .NET, Mono... • Java
  • 5. // C# List<string> keywords = ...; var result = keywords .GroupBy(k => k[0].ToUpper()) .ToDictionary( g => g.Key, g => g.OrderBy(k => k).ToList()); // F# let keywords = ... let result = keywords |> Seq.groupBy (fun k -> k.[0].ToUpper()) |> Seq.map (fun (k, v) -> (k, v |> Seq.sort)) |> Map.ofSeq
  • 6. # Ruby keywords = ... result = keywords .group_by { |k| k[0,1].upcase } .each { |key, value| value.sort! } // JavaScript var keywords = ...; var result = keywords .groupBy(function (k) { return k[0].toUpperCase(); }) .each(function (key, value) { value.sort(); });
  • 7. Java List<String> keywords = ...; Map<Character, List<String>> result = new HashMap<...>(); for (String k: keywords) { char firstChar = k.charAt(0); if (!result.containsKey(firstChar)) { result.put(firstChar, new ArrayList<String>()); } result.get(firstChar).add(k); } for (List<String> list: result.values()) { Collections.sort(list); }
  • 8. * Map<Character, List<String>> result = keyword .groupBy( new F<String, Character> { public Character f(String s) { return s.charAt(0); } }) .toMap( new F<Grouping<Character, String, Character> { public Charactor f(Grouping<Char, String> g) { return g.getKey(); } }, new F<Grouping<Character, String>, List<String>> { public List<String> f(Grouping<Character, String> g) { return g .orderBy( new F<String, String> { public String f(String s) { return s; } }) .toList(); } }); * C# API
  • 11. • • Lambda • •
  • 13. JavaScript • • • prototype • this • apply call arguments constructor callee
  • 16. 1
  • 17. var fib = function () { var state = 0, last0, last1; return { moveNext: function () { if (state == 0) { // this.current = 0; state = 1; } else if (state == 1) { // this.current = 1; var iter = fib(); last1 = 0; while (iter.moveNext()) { state = 2; print(iter.current); } else { } last0 = last1; last1 = this.current; this.current = last0 + last1; } return true; } } }
  • 18. JavaScript 1.7* function fibonacci() { yield 0; yield 1; var a = 0, current = 1; while (true) { for (var i in fibonacci()) { var b = a; print(i); a = current; } current = a + b; yield current; } } * Firefox 2.0+ only: https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators
  • 19. 2
  • 20. var compare = function (x, y) { return x - y; } var swap = function (a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t; } var bubbleSort = function (array) { for (var x = 0; x < array.length; x++) { for (var y = 0; y < array.length - x; y++) { if (compare(array[y], array[y + 1]) > 0) { swap(array, y, y + 1); } } } }
  • 21. var compare = function (x, y, callback) { var innerLoop = function (array, x, y, callback) { setTimeout(10, function () { if (y < array.length - x) { callback(x - y); compare(array[y], array[y + 1], function (r) { }); if (r > 0) { } swap(array, y, y + 1, function () { innerLoop(array, x, y + 1, callback); var swap = function (a, i, j, callback) { }); var t = a[i]; a[i] = a[j]; a[j] = t; } else { repaint(a); innerLoop(array, x, y + 1, callback); } setTimeout(20, callback); }); } } else { callback(); var outerLoop = function (array, x, callback) { } if (x < array) { } innerLoop(array, x, 0, function () { outerLoop(array, x + 1, callback); outerLoop(array, 0, function () { }); console.log("done!"); } else { }); callback(); } }
  • 22. var compare = function (x, y, callback) { var innerLoop = function (array, x, y, callback) { setTimeout(10, function () { if (y < array.length - x) { callback(x - y); compare(array[y], array[y + 1], function (r) { }); if (r > 0) { } swap(array, y, y + 1, function () { innerLoop(array, x, y + 1, callback); var swap = function (a, i, j, callback) { }); var t = a[i]; a[i] = a[j]; a[j] = t; } else { D repaint(a); innerLoop(array, x, y + 1, callback); } M setTimeout(20, callback); }); } } else { T callback(); var outerLoop = function (array, x, callback) { } if (x < array) { } innerLoop(array, x, 0, function () { outerLoop(array, x + 1, callback); outerLoop(array, 0, function () { }); console.log("done!"); } else { }); callback(); } }
  • 23. * • JavaScript DSL • toString • eval * JavaScript ECMAScript 3
  • 25. var f = function () { ... } var f = eval(compile(function () { ... }));
  • 26. var compile = function (f) { // var code = f.toString(); // var ast = parse(code); // return generateCode(ast); }
  • 27. JS • eval “ ” • • • JavaScript JavaScript
  • 28. eval • eval • eval compile • • eval compile • • ECMAScript 5 Strict Mode
  • 29. Jscex
  • 30. Jscex • JavaScript Computation EXpression • JavaScript • F# JavaScript • “ ” • JavaScript JavaScript
  • 31. Jscex • • Jscex JavaScript • • Jscex / • JavaScript / • ECMAScript 3
  • 33. • • • • •
  • 34. var compareAsync = eval(Jscex.compile("async", function (x, y) { $await(Jscex.Async.sleep(10)); // each "compare" takes 10 ms. return x - y; })); var swapAsync = eval(Jscex.compile("async", function (a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t; // swap repaint(a); // repaint after each swap $await(Jscex.Async.sleep(20)); // each "swap" takes 20 ms. })); var bubbleSortAsync = eval(Jscex.compile("async", function (array) { for (var x = 0; x < array.length; x++) { for (var y = 0; y < array.length - x; y++) { var r = $await(compareAsync(array[y], array[y + 1])); if (r > 0) $await(swapAsync(array, y, y + 1)); } } })); http://files.zhaojie.me/jscex/samples/async/sorting-animations.html?bubble
  • 35. var compareAsync = eval(Jscex.compile("async", function (x, y) { $await(Jscex.Async.sleep(10)); // each "compare" takes 10 ms. return x - y; })); var swapAsync = eval(Jscex.compile("async", function (a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t; // swap repaint(a); // repaint after each swap $await(Jscex.Async.sleep(20)); // each "swap" takes 20 ms. })); var bubbleSortAsync = eval(Jscex.compile("async", function (array) { for (var x = 0; x < array.length; x++) { for (var y = 0; y < array.length - x; y++) { var r = $await(compareAsync(array[y], array[y + 1])); if (r > 0) $await(swapAsync(array, y, y + 1)); } } })); http://files.zhaojie.me/jscex/samples/async/sorting-animations.html?bubble
  • 36. Jscex // var somethingAsync = eval(Jscex.compile("async", function (...) { // } ));
  • 37. function () { var res = $await(<async work>); }
  • 38. function () { var res = $await(<async work>); } HTTP UI Web Service
  • 39. var f = eval(Jscex.compile("async", function () { var img = $await(readAsync("http://...")); console.log("loaded!"); $await(writeAsync("./files/...")); console.log("saved!"); }));
  • 40. … var f = eval('(function () { var _b_ = Jscex.builders["async"]; return _b_.Start(this, _b_.Delay(function () { _b_.Bind(readAsync(...), function (img) { console.log("loaded!"); return _b_.Bind(writeAsync(...), function () { console.log("saved!"); return _b_.Normal(); }); }); }) ); })');
  • 41. … var f = (function () { var _b_ = Jscex.builders["async"]; return _b_.Start(this, _b_.Delay(function () { _b_.Bind(readAsync(...), function (img) { console.log("loaded!"); return _b_.Bind(writeAsync(...), function () { console.log("saved!"); return _b_.Normal(); }); }); }) ); });
  • 42. Express var app = express.createServer(); app.get('/', function (req, res) { /** * * * 1. * 2. * * 3. res * * “ ” **/ }); app.listen(3000);
  • 43. Jscex app.getAsync('/', eval(Jscex.compile("async", function (req, res) { var keys = $await(db.getKeysAsync(...)); var results = []; for (var i = 0; i < keys.length; i++) { var r = $await(cache.getAsync(keys[i])); if (!r) { r = $await(db.getItemAsync(keys[i])); } results.push(r); } res.send(generateList(results)); })));
  • 44. Jscex vs. • • • Virtual Panel: How to Survive Asynchronous Programming in JavaScript • • StratifiedJS • Narrative JavaScript • Streamline Jscex
  • 45. Jscex vs. • • • • • Jscex • JavaScript • •
  • 46. Jscex vs. • • • • • Jscex • JavaScript • JavaScript • JavaScript
  • 47. Streamline • Jscex • JavaScript • JIT • • Jscex • • Yield – Resume vs. Asynchronous Callbacks – An Equivalence
  • 48. Streamline (input) var bubbleSortAsync = function (array, _) { for (var x = 0; x < array.length; x++) { for (var y = 0; y < array.length - x; y++) { if (compareAsync(array[y], array[y + 1], _) > 0) swapAsync(array, y, y + 1, _); } } }
  • 49. Streamline (compiled) var bubbleSortAsync = function __1(array, _) { if (!_) { return __future(__1, arguments, 1); } if ((y < (array.length - x))) { ; return compareAsync(array[y], array[(y + 1)], __cb(_, function(__0, r) { var __then = _; if ((r > 0)) { var x = 0; return swapAsync(array, y, (y + 1), __cb(_, __then)); var __4 = false; } return function(__break) { ; var __loop = __nt(_, function() { return __then(); var __then = __loop; })); if (__4) { } x++; else { } return __break(); else { } __4 = true; ; } }); ; return __loop(); if ((x < array.length)) { }(__then); var y = 0; } var __3 = false; else { return function(__break) { return __break(); var __loop = __nt(_, function() { } var __then = __loop; ; if (__3) { }); y++; return __loop(); } }(__then); else { }; __3 = true; } ; http://sage.github.com/streamlinejs/examples/streamlineMe.html
  • 50. Jecex (input) var bubbleSortAsync = eval(Jscex.compile("async", function (array) { for (var x = 0; x < array.length; x++) { for (var y = 0; y < array.length - x; y++) { var r = $await(compareAsync(array[y], array[y + 1])); if (r > 0) $await(swapAsync(array, y, y + 1)); } } }));
  • 51. Jecex (compiled) var bubbleSortAsync = (function (array) { var _b_ = Jscex.builders["async"]; return _b_.Start(this, _b_.Delay(function () { var x = 0; return _b_.Loop( function () { return x < array.length; }, function () { x++; }, _b_.Delay(function () { var y = 0; return _b_.Loop( function () { return y < (array.length - x); }, function () { y++; } _b_.Delay(function () { return _b_.Bind(compareAsync(array[y], array[y + 1]), function (r) { if (r > 0) { return _b_.Bind(swapAsync(array, y, y + 1), function () { return _b_.Normal(); }); } else { return _b_.Normal(); } }); }), false ); }), false ); }) ); })
  • 52. Jecex (compiled) var bubbleSortAsync = (function (array) { var _b_ = Jscex.builders["async"]; return _b_.Start(this, _b_.Delay(function () { outer loop var x = 0; return _b_.Loop( function () { return x < array.length; }, function () { x++; }, _b_.Delay(function () { var y = 0; return _b_.Loop( inner loop function () { return y < (array.length - x); }, function () { y++; } _b_.Delay(function () { return _b_.Bind(compareAsync(array[y], array[y + 1]), function (r) { if (r > 0) { return _b_.Bind(swapAsync(array, y, y + 1), function () { $await(compareAsync(...)) return _b_.Normal(); }); } else { $await(swapAsync(...)) return _b_.Normal(); } }); }), false ); }), false ); }) ); })
  • 53. Jscex • • • “debugger” • JavaScript • Start, Delay, Combine • Loop, Try • Normal, Return, Break, Continue, Throw • Bind
  • 56. ... the principle we go by is, don't expect to see a particular concurrency model put into C# because there're many different concurrency model ... it's more about finding things are common to all kinds of concurrency ... - Anders Hejlsberg
  • 57. • JIT • AOT • • F# Scala Python Twisted C# vNext • Python C# JavaScript 1.7 • …
  • 58. Jscex • • “ ” • “ ” •
  • 59. // var fib = eval(Jscex.compile("seq", function () { $yield(0); $yield(1); var a = 0, current = 1; while (true) { var b = a; a = current; current = a + b; $yield(current); } })); https://github.com/JeffreyZhao/jscex/blob/master/samples/seq/fib.html
  • 60. fib() .filter(function (n) { return n % 2 == 0; }) .skip(2) .take(5) .zip(infinite(1)) .map(function (a) { return a[1] + ": " + a[0]; }) .each(print); https://github.com/JeffreyZhao/jscex/blob/master/samples/seq/fib.html
  • 61. var filter = eval(Jscex.compile("seq", function (iter, predicate) { while (iter.moveNext()) { if (predicate(iter.current)) { $yield(iter.current); } } })); var map = eval(Jscex.compile("seq", function (iter, mapper) { while (iter.moveNext()) { $yield(mapper(iter.current)); } })); var zip = eval(Jscex.compile("seq", function (iter1, iter2) { while (iter1.moveNext() && iter2.moveNext()) { $yield([iter1.current, iter2.current]); } })); https://github.com/JeffreyZhao/jscex/blob/master/src/jscex.seq.powerpack.js
  • 62. Maybe Monad var maybeFunc = function () { var maybeA = getA(); if (maybeA != Maybe.None) { var maybeB = getB(); if (maybeB != Maybe.None) { return maybeA.value + maybeB.value; } else { return Maybe.None; } } else { return Maybe.None; } } // var maybeFunc = eval(Jscex.compile("maybe", function () { var a = $try(getA()); var b = $try(getB()); return a + b; }));
  • 63. JavaScirpt DSL • + • JavaScript “ ” • Jscex • BSD • https://github.com/JeffreyZhao/jscex • http://www.sndacode.com/projects/jscex
  • 64. Q &A