Posterous theme by Cory Watilo

Pub/Sub (Dustin Diaz's)

See Diaz’s article.

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

function Publisher(name) {
    this.name = name;
    this.subscribers = [];
}
Publisher.prototype.deliver = function (data, scope) {
    scope = scope || window;

    var self = this;

    this.subscribers.forEach(
        function (value) {
            value.call(scope, self.name, data);
        }
    );

    return this;
};
Function.prototype.subscribe = function (publisher) {
    var self = this,
        isExistent = publisher.subscribers.some(
            function (value) {
                return (value === self);
            }
        );

    if (!isExistent) {
        publisher.subscribers.push(this);
    }

    return this;
};
Function.prototype.unsubscribe = function (publisher) {
    var self = this;

    publisher.subscribers = publisher.subscribers.filter(
        function(value) {
            if (value !== self) {
                return value;
            }
        }
    );

    return this;
};

More FizzBuzz

A functional version (won’t work in IE).

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

See my original FizzBuzz.

(function (n) {
    var r = [];

    while (n--) {
        r.push(n + 1);
    }

    return r.reverse();
})(100).map(function (n) {
    return !(n % 15) ?
        'FizzBuzz' :
        !(n % 3) ?
            'Fizz' :
            !(n % 5) ?
                'Buzz' :
                n;
});

Playing With node.js

Streaming a PNG in node.js

var sys = require('sys'),
    http = require('http'),
    url = require('url');

http.createServer(function (request, response) {
    var f = (url.parse(request.url, true)).query.file
        fs = require('fs'),
        path = './' + f,
        rs = fs.createReadStream(path);

    response.writeHead(200, { 'Content-Type': 'image/png' });
    rs.addListener('data', function (b) {
        response.write(b, 'binary');
    });
    rs.addListener('end', function () { response.end(); })
}).listen(8000);

sys.puts('Server running at http://127.0.0.1:8000/');

My FizzBuzz

See Jeff Atwood’s article.

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

var fizzBuzz = function (n) {
  n = n || 100;

  var i = 0,
      r = [];

  while (i++ < n) {
    r.push(
      (!(i % 3) &&  (i % 5)) && ('Fizz (' + i + ')')     ||
      ( (i % 3) && !(i % 5)) && ('Buzz (' + i + ')')     ||
      (!(i % 3) && !(i % 5)) && ('FizzBuzz (' + i + ')') ||
      i
    );
  }

  return r.join('<br />');
};

document.getElementById('result').innerHTML = fizzBuzz();