Permalink
Browse files

seems to work

  • Loading branch information...
0 parents commit bf2196f803ca07e4bc5d749f81be6a82dbee1671 @substack committed Apr 16, 2012
Showing with 82 additions and 0 deletions.
  1. +38 −0 README.markdown
  2. +7 −0 example/work.js
  3. +37 −0 index.js
38 README.markdown
@@ -0,0 +1,38 @@
+marx
+====
+
+Allocate worker roles among a collective of workers according to their
+abilities.
+
+example
+=======
+
+work.js
+
+``` js
+var marx = require('marx');
+
+var work = { web : 3, auth : 2, logger : 1 };
+var workers = { a : 2, b : 1, c : 5 };
+
+var shares = marx(workers, work);
+console.dir(shares);
+```
+
+output
+
+```
+$ node work.js
+```
+
+methods
+=======
+
+``` js
+var marx = require('marx')
+```
+
+marx(workers, work)
+-------------------
+
+Return an object which how many of each type of work each worker should perform.
7 example/work.js
@@ -0,0 +1,7 @@
+var marx = require('../');
+
+var work = { web : 3, auth : 2, logger : 1 };
+var workers = { a : 2, b : 1, c : 5 };
+
+var shares = marx(workers, work);
+console.dir(shares);
37 index.js
@@ -0,0 +1,37 @@
+module.exports = function (workers, work) {
+ var shares = {};
+ var jobs = Object.keys(work);
+
+ jobs.forEach(function (job) {
+ for (var n = work[job]; n > 0; n--) {
+ var id = mostIdle(workers, shares) || '_overflow';
+
+ if (!shares[id]) shares[id] = {};
+ shares[id][job] = (shares[id][job] || 0) + 1;
+ }
+ });
+
+ return shares;
+};
+
+function mostIdle (workers, usage) {
+ var load = Object.keys(workers).reduce(function (acc, id) {
+ var procs = Object.keys(usage[id] || {})
+ .reduce(function (sum, job) {
+ return sum + ((usage[id] || {})[job] || 0);
+ }, 0)
+ ;
+ var capacity = workers[id];
+ var n = procs / capacity;
+ acc[n] = id;
+
+ return acc;
+ }, {});
+
+ var free = Object.keys(load)
+ .filter(function (frac) { return frac < 1.0 })
+ .sort()
+ ;
+
+ return free[0] && load[free[0]];
+}

0 comments on commit bf2196f

Please sign in to comment.