Foundations.Control

This library provides a version of MapReduce using Futures, Palm's mechanism for handling asynchronous callbacks.

Control.mapReduce

{ item: <original data>, result: <normal result>, exception: <error result> }

Only "result" or "exception" is present, never both.

By default, any exceptions in map are propagated to reduce and the returned future. To suppress or otherwise override this behavior, implement reduce.

Syntax

    Future mapReduce(config, data)

Parameters

Argument Required Type Description
config Yes object Object containing map and reduce functions.
data Yes any array The map function is applied iteratively to each element in the dataset.

Returns

Future containing results.

Example

var libraries = MojoLoader.require({ name: "foundations", version: "1.0" });
var Future    = libraries["foundations"].Control.Future;
var mapReduce = libraries["foundations"].Control.mapReduce;
var data = [
  {name: "duck", say: "quack", after: 300},
  {name: "duck", say: "quack", after: 100},
  {name: "goose", say: "quark", after: 200}
];

function map(animal) {
  var f = new Future();
  setTimeout(function() {
      try {
          f.result = [animal.name, " has this much to say: ", animal.say].join();
      } catch (e) {
          f.exception = e;
      }
  }, animal.after);
  return f;
};

function reduce(results) {
  // do not throw errors, just pass them through
  return new Future().immediate(results);
};

var future = mapReduce( { map: map, reduce: reduce }, data);

future.then(function() {                
  var result = future.result;
  Mojo.Log.info("mapReduce ="+JSON.stringify(result));
});

Example Output

mapReduce =
[
  {
      "item":{
          "name":"duck",
          "say":"quack",
          "after":100
      },
      "result":"duck, has this much to say: ,quack"
  },
  {
      "item":{
          "name":"goose",
          "say":"quark",
          "after":200
      },
      "result":"goose, has this much to say: ,quark"
  },
  {
      "item":{
          "name":"duck",
          "say":"quack",
          "after":300
      },
      "result":"duck, has this much to say: ,quack"
  }
]