Permalink
Browse files

* datatype.js: added _.multi

  • Loading branch information...
1 parent ad64eb2 commit 57cfa6c494cfc4e51cf424ee1bfb8782c210f7d8 David Nolen committed May 18, 2010
Showing with 29 additions and 6 deletions.
  1. +29 −6 datatype.js
View
@@ -1,11 +1,29 @@
+(function() {
+
+var multiMap = {};
+
_.mixin({
extenderOf: function(x, protocol) {
return _(x.protocols).indexOf(protocol) != -1;
},
+ multi: function(name, type, fn) {
+ if(_.isUndefined(multiMap[name])) {
+ var dispatchTable = {};
+ multiMap[name] = dispatchTable;
+ var dispatcher = {};
+ dispatcher[name] = function(instance) {
+ var rest = _.rest(arguments);
+ return multiMap[name][instance.name].apply(instance, rest);
+ };
+ _.mixin(dispatcher);
+ }
+ multiMap[name][type.name] = fn;
+ },
+
protocol: function(obj) {
obj.toString = function() {
- return ["<Protocol: ", (obj.name || "Unnamed protocol"), ">"].join("");
+ return ["<Protocol: ", (obj.name || _uniqueId("UnnamedProtocol")), ">"].join("");
};
return obj;
},
@@ -18,19 +36,24 @@ _.mixin({
return this;
}
};
- var methodMap = obj.protocols
+ var protocols = obj.protcols || [];
+ var name = obj.name = (obj.name || _.uniqueId("UnnamedType"));
+ var methodMap = protocols
.map(function(x) { x = _(x).clone(); delete x.name; delete x.toString; return x; });
- obj =_.reduce((methodMap || []).concat(obj), {}, function(memo, m) {
+ obj =_.reduce(methodMap.concat(obj), {}, function(memo, m) {
return _.extend(memo, m);
});
obj = _(obj).extend({
toString: function() {
- return ["<Type: ", this.name, ">"].join("");
+ return ["<Type: ", name, ">"].join("");
}
});
+ klass.name = name;
klass.prototype = obj;
klass.prototype.type = klass;
- klass.prototype.protocols = klass.protocols = obj.protocols;
+ klass.prototype.protocols = klass.protocols = protocols;
return klass;
}
-});
+});
+
+})();

0 comments on commit 57cfa6c

Please sign in to comment.