Angular and Parallel

by codef0rmer

HTML

<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div>
    <input ng-model="name" />
    <span ng-bind="name"></span>
</div>

JavaScript

var App = angular.module('App', []);
App.run(function($rootScope) {
    $rootScope.looper = function(n) {
        var i = 0, arr = [];
        while (++i < n * n) {
            arr.push(i);
        }
        return arr;
    };
    
    $rootScope.$watch('name', function(newVal, oldVal) {
        if (newVal && newVal !== oldVal) {
            var p = new Parallel(100);
            p.spawn($rootScope.looper).then(function(response) {/*console.log(response);*/});
        }
    });
});


(function () {
	var isNode = typeof module !== 'undefined' && module.exports;
	var setImmediate = setImmediate || function (cb) {
		setTimeout(cb, 0);
	};
	var Worker = isNode ? require(__dirname + '/Worker.js') : self.Worker;

	function extend(from, to) {
		if (!to) to = {};
		for (var i in from) {
			if (to[i] === undefined) to[i] = from[i];
		}
		return to;
	}

	function Operation() {
		this._callbacks = [];
		this._errCallbacks = [];

		this._resolved = 0;
		this._result = null;
	}

	Operation.prototype.resolve = function (err, res) {
		if (!err) {
			this._resolved = 1;
			this._result = res;

			for (var i = 0; i < this._callbacks.length; ++i) {
				this._callbacks[i](res);
			}
		} else {
			this._resolved = 2;
			this._result = err;

			for (var iE = 0; iE < this._errCallbacks.length; ++iE) {
				this._errCallbacks[iE](res);
			}
		}

		this._callbacks = [];
		this._errCallbacks = [];
	};

	Operation.prototype.then = function (cb, errCb) {
		if (this._resolved === 1) { // result
			if (cb) {
				cb(this._result);
			}

			return;
		} else if (this._resolved === 2) { // error
			if (errCb) {
				errCb(this._result);
			}
			return;
		}

		if (cb) {
			this._callbacks[this._callbacks.length] = cb;
		}

		if (errCb) {
			this._errCallbacks[this._errCallbacks.length] = errCb;
		}
		return this;
	};

	var defaults = {
		evalPath: isNode ? __dirname + '/eval.js' : null,
		maxWorkers: isNode ? require('os').cpus().length : 4,
		synchronous: true
	};

	function Parallel(data,...