Posted By

codernator on 12/27/12


Tagged

closure


Versions (?)

GeneratorModule: Array Creation Inspired by Python's List Comprehension


 / Published in: JavaScript
 

The inspiration for this module comes from Python's list comprehension: [x for x in range(10)]. The idea is to replace a for-loop with something more condensed. However, since such syntax is completely foreign to Javascript, that operation looks more like: app.genList(app.rangeGenerator(0, 10)).

Requires ObjectBoilerPlateModule.

GeneratorModule comes with four "public" methods:

  • getGeneratorModuleVersion - useful to test for existence of module.
  • arrayGenerator - iterate over an array, optionally filtering items from the array with a predicate argument.
  • rangeGenerator - iterate over a number sequence from min to max.
  • genList - create an array using either an arrayGenerator or a rangeGenerator, optionally morphing elements from the generator into a new data type.

This is implemented using module pattern. To inject the functions into the global namespace, simply invoke the GeneratorModule method. Otherwise, the functions can be added to an existing object using GeneratorModule.call([object]).

Examples:

function test() {
    "use strict";

    function reportNumber(number) {
        return number + " is " + (number % 2 === 0 ? "even" : "odd") + ".";
    }

    function reportLetter(letter) {
        return "The letter is " + letter + ".";
    }

    function isMultipleOf3(number) {
        return number % 3 === 0;
    }

    var app = {};
    ObjectBoilerPlateModule.call(app);
    GeneratorModule.call(app, app);
    console.log(app.toList(app.range(0, 10)));
    // [0,1,2,3,4,5,6,7,8,9]

    console.log(app.toList(reportNumber, app.range(0, 15), isMultipleOf3));
    // ["0 is even.", "3 is odd.", "6 is even.", "9 is odd.", "12 is even."]

    console.log(app.toList(app.inArray(["a", "d", 'q'])));
    // ["a", "d", "q"]

    console.log(app.toList(reportLetter, app.inArray(["a", "d", 'q']), function (x) { return x === "a"; }));
    // ["The letter is a."]
}

Limitations/Considerations:

  • Like Python generators, only 1 iteration will function - the generators do not come with a "reset" method.
  • The ArrayGenerator objects hold reference to "list" passed in the constructor. If there is code between creating the generator and invoking it (say with genList), it is possible the contents of "list" will change. (This could be mitigated by having the ArrayGenerator constructor perform a deep copy "list"...)

Report this snippet  

You need to login to post a comment.