Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Open an arbitrary number of resources safely in ruby

I'm too lazy to work out what happens if I try
filenames.map {|f| File.open(f) }
and the thirteenth file doesnt exist, but I bet I don't like it.

module Enumerable
  # Example:
  # ['a','b'].with_files {|f,g| ... }
  # is the same as
  # File.open('a') {|f| File.open('b') {|g| ... } }
  # You can specify modes with
  # [['a', 'rb'], ['b', 'w']].with_files ...
  def with_files(
      meth = File.method(:open),
      offset=0,
      inplace=false,
      &block
  )
    if inplace then
      if offset >= length then
        yield self
      else
        fname,mode = *self[offset]
        File.open(fname,mode) {|f| 
          self[offset] = f
          self.with_files(meth,offset+1,true,&block)
        }
      end
    else
      dup.with_files(meth,offset,true,&block)
    end
  end
end

Leak Free Javascript Closures

Javascript closures can be a powerful programming technique. Unfortunately in Internet Explorer they are a common source of memory leaks. Therefore I propose a method to create closures that don't leak memory.

Solution:

Function.prototype.closure = function(obj)
{
  // Init object storage.
  if (!window.__objs)
  {
    window.__objs = [];
    window.__funs = [];
  }

  // For symmetry and clarity.
  var fun = this;

  // Make sure the object has an id and is stored in the object store.
  var objId = obj.__objId;
  if (!objId)
    __objs[objId = obj.__objId = __objs.length] = obj;

  // Make sure the function has an id and is stored in the function store.
  var funId = fun.__funId;
  if (!funId)
    __funs[funId = fun.__funId = __funs.length] = fun;

  // Init closure storage.
  if (!obj.__closures)
    obj.__closures = [];

  // See if we previously created a closure for this object/function pair.
  var closure = obj.__closures[funId];
  if (closure)
    return closure;

  // Clear references to keep them out of the closure scope.
  obj = null;
  fun = null;

  // Create the closure, store in cache and return result.
  return __objs[objId].__closures[funId] = function ()
  {
    return __funs[funId].apply(__objs[objId], arguments);
  };
};


Usage example:

function attach()
{
  var element = document.getElementById("my-element");
  element.attachEvent("onclick", function()
    {
      alert("Clicked: " + this.innerHTML);
    }.closure(element));
}


So now we have truly leak free closures.

In addition we can also easily remove an object from the global array. The following code allows the garbage collector to free an object if there are no other references to it:

window.__objs[obj.__objId] = null;


Source: Leak Free Javascript Closures

JavaScript versions of the functions described in Martin Fowler's article "CollectionClosureMethod"

See the original article at http://www.martinfowler.com/bliki/CollectionClosureMethod.html.

These implement all the methods except the sorting related ones.
Array.prototype.select = function(detect) {
    var result = [];
    for (var i = 0; i < this.length; ++i) {
        if (detect(this[i])) {
            result.push(this[i]);
        }
    }
    return result;
};

Array.prototype.reject = function(detect) {
    var result = [];
    for (var i = 0; i < this.length; ++i) {
        if (!detect(this[i])) {
            result.push(this[i]);
        }
    }
    return result;
};

Array.prototype.partition = function(detect) {
    var yeses = [];
    var nos   = [];
    for (var i = 0; i < this.length; ++i) {
        if (detect(this[i])) {
            yeses.push(this[i]);
        } else {
            nos.push(this[i]);
        }
    }
    return [yeses, nos];
};

Array.prototype.all = function(detect) {
    for (var i = 0; i < this.length; ++i) {
        if (!detect(this[i])) {
            return false;
        }
    }
    return true;
};

Array.prototype.any = function(detect) {
    for (var i = 0; i < this.length; ++i) {
        if (detect(this[i])) {
            return true;
        }
    }
    return false;
};

Array.prototype.find = function(detect, ifNone) {
    for (var i = 0; i < this.length; ++i) {
        if (detect(this[i])) {
            return this[i];
        }
    }

    if (ifNone === null) {
        return null;
    }

    return ifNone();
};

Array.prototype.map = function(mapper) {
    var result = [];
    for (var i = 0; i < this.length; ++i) {
        result.push(mapper(this[i]));
    }
    return result;
};

Array.prototype.inject = function(initial, reducer) {
    var result = initial;
    for (var i = 0; i < this.length; ++i) {
        result = reducer(result, this[i]);
    }
    return result;
};
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS