Object collection API
This has probably been done before, but I decided to spend a few minutes this morning creating a proof of concept for it. The objective is to create a function that accepts multiple objects and returns an API that mimics the objects' APIs, but applies the named method to all of the objects in the group in turn.
So, if you have an object x and an object y, and both have a function foo(), you can call group(x,y).foo().
Here's my 5 minute POC:
var _A = Array.prototype,
_sl = function (_) { return _A.slice.call(_); },
_jn = function (_,x) { return _A.join.call(_,x); };
function group() {
var _ = _sl(arguments),i,len,
results = [],
methods = {},m,
out = {
results : function () { return results; },
exec : function (fn) {
var a = _sl(arguments)
a.shift();
results = [];
for (i=0,len=_.length; i<len; ++i) {
results.push(fn.call(null,_[i],a));
}
return this;
}
};
for (m in _[0]) {
if (typeof _[0][m] === 'function') {
methods[m] = true;
}
}
for (i=1,len=_.length; i<len; ++i) {
for (m in methods) {
if (typeof _[i][m] !== 'function') {
delete methods[m];
}
}
}
for (m in methods) {
out[m] = (function (meth) {
return function () {
results = [];
for (i=0,len=_.length; i<len; ++i) {
results.push(_[i][meth].apply(_[i],arguments));
}
return this;
};
})(m);
}
return out;
};
For kicks, I made it chainable, too, so each API method will return this. Results of the method calls are accessible via the results() API method.
You can see it in action here.
I decided to only expose functions and only those that were common amongst all objects passed in. It would have been easy enough to create API methods for all discovered methods and ignore objects that didn't have the requested method or just execute an empty stub. But hey, POC, right? And of course, it doesn't handle asynchronous operations via setTimeout or XHR.