Posterous theme by Cory Watilo

Async Method Queue Chaining (Dustin Diaz)

See Diaz’s article.

Head over to remy sharp’s JS Bin and play.

var Queue = function () {
  if (!(this instanceof arguments.callee)) {
      return new arguments.callee();
  }
  this._methods = [];
  this._response = null;
  this._flushed = false;
}

Queue.prototype = {
  add: function(fn) {
    (this._flushed) ?
      fn(this._response) :
      this._methods.push(fn);
  },
  flush: function(resp) {
    (this._flushed) && (return);
    this._response = resp;
    this._flushed = true;
    while (this._methods[0]) {
      this._methods.shift()(resp);
    }
  }
};

My "waitUntil" method

Head over to remy sharp’s JS Bin and play.

Function.prototype.waitUntil = function (condition, interval) {
    interval = interval || 100;

    var fn = this,
        shell = function () {
            var timer = setInterval(
                function () {
                    var check;

                    try {
                        check = !!(condition());
                    } catch (e) {
                        check = false;
                    }

                    if (check) {
                        clearInterval(timer);
                        delete timer;
                        fn();
                    }
                },
                interval
            );
        };

    return shell;
};

var done = false;

(function () {
    document.getElementById('result').innerHTML = 'I waited...';
}).waitUntil(function () { return !!(done); })();

setTimeout(function () { done = true; }, 2000);

The Y Combinator (Crockford)

See Crockford’s article.

Head over to remy sharp’s JS Bin and play.

var Y = function (le) {
  return ((function (f) {
    return f(f);
  })(function (f) {
    return le(function (x) {
      return f(f)(x);
    });
  }));
};

var factorial = Y(function (fac) {
  return function (n) {
    return (n <= 2) ? n : n * fac(n - 1);
  };
});

!!(factorial(5) === 120); //true