Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Revert "Revert "Make circular require()'s and exception.""

This reverts commit 2aa46aa.
  • Loading branch information...
commit 9878d97f7acc89a5e90b921a212e49e94cd0becd 1 parent aa15ac6
@agrieve agrieve authored
Showing with 50 additions and 1 deletion.
  1. +18 −1 lib/scripts/require.js
  2. +32 −0 test/test.require.js
View
19 lib/scripts/require.js
@@ -24,6 +24,10 @@ var require,
(function () {
var modules = {};
+ // Stack of moduleIds currently being built.
+ var requireStack = [];
+ // Map of module ID -> index into requireStack of modules currently being built.
+ var inProgressModules = {};
function build(module) {
var factory = module.factory;
@@ -36,8 +40,21 @@ var require,
require = function (id) {
if (!modules[id]) {
throw "module " + id + " not found";
+ } else if (id in inProgressModules) {
+ var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id;
+ throw "Cycle in require graph: " + cycle;
}
- return modules[id].factory ? build(modules[id]) : modules[id].exports;
+ if (modules[id].factory) {
+ try {
+ inProgressModules[id] = requireStack.length;
+ requireStack.push(id);
+ return build(modules[id]);
+ } finally {
+ delete inProgressModules[id];
+ requireStack.pop();
+ }
+ }
+ return modules[id].exports;
};
define = function (id, factory) {
View
32 test/test.require.js
@@ -56,6 +56,38 @@ describe("require + define", function () {
}).toThrow("module your mom not found");
});
+ it("throws an exception when modules depend on each other", function () {
+ define("ModuleA", function(require, exports, module) {
+ require("ModuleB");
+ });
+ define("ModuleB", function(require, exports, module) {
+ require("ModuleA");
+ });
+ expect(function () {
+ require("ModuleA");
+ }).toThrow("Cycle in require graph: ModuleA->ModuleB->ModuleA");
+ define.remove("ModuleA");
+ define.remove("ModuleB");
+ });
+
+ it("throws an exception when a cycle of requires occurs", function () {
+ define("ModuleA", function(require, exports, module) {
+ require("ModuleB");
+ });
+ define("ModuleB", function(require, exports, module) {
+ require("ModuleC");
+ });
+ define("ModuleC", function(require, exports, module) {
+ require("ModuleA");
+ });
+ expect(function () {
+ require("ModuleA");
+ }).toThrow("Cycle in require graph: ModuleA->ModuleB->ModuleC->ModuleA");
+ define.remove("ModuleA");
+ define.remove("ModuleB");
+ define.remove("ModuleC");
+ });
+
it("calls the factory method when requiring", function () {
var factory = jasmine.createSpy();
define("dino", factory);
Please sign in to comment.
Something went wrong with that request. Please try again.