SlideShare ist ein Scribd-Unternehmen logo
1 von 65
Downloaden Sie, um offline zu lesen
JavaScript
“      ”
       - 2011.7
•       /       / Jeffrey Zhao /

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

•         @

• F#, JavaScript, Scala, C#, Python, .NET, Mono...
• Java
// 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
•
•
• prototype
• this
• apply call   arguments constructor
  callee
JavaScript Ninja
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
•
    •
    •
•
    •
    •
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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?
 

Mehr von 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
 

Mehr von 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)
 

Kürzlich hochgeladen

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 

Kürzlich hochgeladen (20)

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 

Javascript Uncommon Programming

  • 1. JavaScript “ ” - 2011.7
  • 2. / / Jeffrey Zhao / • • http://blog.zhaojie.me/ • @ • F#, JavaScript, Scala, C#, Python, .NET, Mono... • Java
  • 3.
  • 4.
  • 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 • •
  • 12.
  • 13. JavaScript • • • prototype • this • apply call arguments constructor callee
  • 15.
  • 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
  • 32.
  • 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
  • 54.
  • 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