listcomp.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. if(!dojo._hasResource["dojox.lang.functional.listcomp"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojox.lang.functional.listcomp"] = true;
  8. dojo.provide("dojox.lang.functional.listcomp");
  9. // This module adds high-level functions and related constructs:
  10. // - list comprehensions similar to JavaScript 1.7
  11. // Notes:
  12. // - listcomp() produces functions, which after the compilation step are
  13. // as fast as regular JS functions (at least theoretically).
  14. (function(){
  15. var g_re = /\bfor\b|\bif\b/gm;
  16. var listcomp = function(/*String*/ s){
  17. var frag = s.split(g_re), act = s.match(g_re),
  18. head = ["var r = [];"], tail = [], i = 0, l = act.length;
  19. while(i < l){
  20. var a = act[i], f = frag[++i];
  21. if(a == "for" && !/^\s*\(\s*(;|var)/.test(f)){
  22. f = f.replace(/^\s*\(/, "(var ");
  23. }
  24. head.push(a, f, "{");
  25. tail.push("}");
  26. }
  27. return head.join("") + "r.push(" + frag[0] + ");" + tail.join("") + "return r;"; // String
  28. };
  29. dojo.mixin(dojox.lang.functional, {
  30. buildListcomp: function(/*String*/ s){
  31. // summary: builds a function from a text snippet, which represents a valid
  32. // JS 1.7 list comprehension, returns a string, which represents the function.
  33. // description: This method returns a textual representation of a function
  34. // built from the list comprehension text snippet (conformant to JS 1.7).
  35. // It is meant to be evaled in the proper context, so local variable can be
  36. // pulled from the environment.
  37. return "function(){" + listcomp(s) + "}"; // String
  38. },
  39. compileListcomp: function(/*String*/ s){
  40. // summary: builds a function from a text snippet, which represents a valid
  41. // JS 1.7 list comprehension, returns a function object.
  42. // description: This method returns a function built from the list
  43. // comprehension text snippet (conformant to JS 1.7). It is meant to be
  44. // reused several times.
  45. return new Function([], listcomp(s)); // Function
  46. },
  47. listcomp: function(/*String*/ s){
  48. // summary: executes the list comprehension building an array.
  49. return (new Function([], listcomp(s)))(); // Array
  50. }
  51. });
  52. })();
  53. }