Simple JavaScript Module "Loader"
The names define and defined are too similar, which could lead to mistakes. I suggest renaming the latter to isDefined.



You could flatten some of the conditionals when all branches leave the block. For example:

// If we have already seen this id on the require stack, we've got
// some form of cyclic dependency.
if (stack.indexOf(id) !== -1 &amp;&amp; stack.push(id)) {
  throw new Error('cyclic dependency: ' + stack.join(' -&gt; '));
}
stack.push(id);

// If we already have an instance for this module, return it.
if (instances.hasOwnProperty(id)) {
  return instances[id];
}

if (typeof(definitions[id]) === 'function') {
  // Otherwise if our definition is a function, call it and pass the
  // require method to it.
  return instances[id] = definitions[id].call(null, internalRequire);
}

// Otherwise just return the definition itself (useful for objects
// e.g. constants).
return instances[id] = definitions[id];