listcomp.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // wrapped by build app
  2. define("dojox/lang/functional/listcomp", ["dijit","dojo","dojox"], function(dijit,dojo,dojox){
  3. dojo.provide("dojox.lang.functional.listcomp");
  4. // This module adds high-level functions and related constructs:
  5. // - list comprehensions similar to JavaScript 1.7
  6. // Notes:
  7. // - listcomp() produces functions, which after the compilation step are
  8. // as fast as regular JS functions (at least theoretically).
  9. (function(){
  10. var g_re = /\bfor\b|\bif\b/gm;
  11. var listcomp = function(/*String*/ s){
  12. var frag = s.split(g_re), act = s.match(g_re),
  13. head = ["var r = [];"], tail = [], i = 0, l = act.length;
  14. while(i < l){
  15. var a = act[i], f = frag[++i];
  16. if(a == "for" && !/^\s*\(\s*(;|var)/.test(f)){
  17. f = f.replace(/^\s*\(/, "(var ");
  18. }
  19. head.push(a, f, "{");
  20. tail.push("}");
  21. }
  22. return head.join("") + "r.push(" + frag[0] + ");" + tail.join("") + "return r;"; // String
  23. };
  24. dojo.mixin(dojox.lang.functional, {
  25. buildListcomp: function(/*String*/ s){
  26. // summary: builds a function from a text snippet, which represents a valid
  27. // JS 1.7 list comprehension, returns a string, which represents the function.
  28. // description: This method returns a textual representation of a function
  29. // built from the list comprehension text snippet (conformant to JS 1.7).
  30. // It is meant to be evaled in the proper context, so local variable can be
  31. // pulled from the environment.
  32. return "function(){" + listcomp(s) + "}"; // String
  33. },
  34. compileListcomp: function(/*String*/ s){
  35. // summary: builds a function from a text snippet, which represents a valid
  36. // JS 1.7 list comprehension, returns a function object.
  37. // description: This method returns a function built from the list
  38. // comprehension text snippet (conformant to JS 1.7). It is meant to be
  39. // reused several times.
  40. return new Function([], listcomp(s)); // Function
  41. },
  42. listcomp: function(/*String*/ s){
  43. // summary: executes the list comprehension building an array.
  44. return (new Function([], listcomp(s)))(); // Array
  45. }
  46. });
  47. })();
  48. });