SlideShare a Scribd company logo
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

More Related Content

What's hot

Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performanceDuoyi Wu
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
scalaconfjp
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
Christian Baranowski
 
Swift internals
Swift internalsSwift internals
Swift internals
Jung 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 2015
Leonardo Borges
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
Wanbok Choi
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
Shaul Rosenzwieg
 
12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine12 Monkeys Inside JS Engine
12 Monkeys Inside JS Engine
ChengHui Weng
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017
Wanbok Choi
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
Ramesh 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 Development
vito jeng
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined Functions
Christoph Bauer
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
andyrobinson8
 
Intro to Pig UDF
Intro to Pig UDFIntro to Pig UDF
Intro to Pig UDF
Chris Wilkes
 
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
CISPA Helmholtz Center for Information Security
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 

What's hot (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
 

Similar to 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
Monadologie
league
 
ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
monikagupta18jan
 
ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changeshayato
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Dmitry Sheiko
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_onefuturespective
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
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
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
Knoldus Inc.
 
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 dummies
santiagoaguiar
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional Programming
Sergey Shishkin
 
Ecma script 5
Ecma script 5Ecma script 5
Ecma script 5
Alexander Tarasyuk
 
Millionways
MillionwaysMillionways
Millionways
Brian Lonsdorf
 
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
 

Similar to 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?
 

More from 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 Life
jeffz
 
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
 

More from 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)
 

Recently uploaded

Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 

Recently uploaded (20)

Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 

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