Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View fib.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
{ "exports": "fib",
"signature": [
{
"name": "fib",
"synopsis": "runs a fibonacci sequence",
"verb": "POST",
"parameters": [
{"name": "number", "required":true, "description":"which fibonacci to calculate"}
]
},
{
"name": "randomfib2",
"synopsis": "runs a random fibonacci sequence, 1 to 30, using a long-lived worker process"
},
{
"name": "randomfib3",
"synopsis": "runs a random fibonacci sequence, 1 to 30, using multiple long-lived worker processes"
}
],
"path": "fib"
}
View fib.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#!/usr/bin/env node
 
var perfectapi = require('perfectapi.js');
var path = require('path');
 
var configPath = path.resolve(__dirname, 'fib.json');
var parser = new perfectapi.Parser();
 
var worker = require('child_process').fork(__dirname + '/fibworker.js');
var callbacks = {};
var requestNum = 0;
worker.on('message', function(m) {
var callback = callbacks[m.id];
delete callbacks[m.id];
callback(null, m.result);
})
 
var numWorkers = require('os').cpus().length;
var nextWorker = 0;
var workers = [];
for (var i=0;i<numWorkers;i++) {
var worker = require('child_process').fork(__dirname + '/fibworker.js');
workers.push(worker);
worker.on('message', function(m) {
var callback = callbacks[m.id];
delete callbacks[m.id];
callback(null, m.result);
})
}
//handle the commands
parser.on('fib', function(config, callback) {
var n = config.number;
if (n<1 || n>40) {
callback('n must be between 1 and 40');
} else {
callback(null, fibonacci(n))
}
})
 
parser.on('randomfib2', function(config, callback) {
requestNum += 1;
callbacks[requestNum] = callback;
var n = Math.ceil(Math.random()*30)
worker.send({n: n, id: requestNum});
})
 
parser.on('randomfib3', function(config, callback) {
requestNum += 1;
callbacks[requestNum] = callback;
var n = Math.ceil(Math.random()*30);
//round robin workers
var worker = workers[nextWorker];
nextWorker += 1;
if (nextWorker == workers.length) nextWorker = 0;
worker.send({n: n, id: requestNum});
})
 
//expose the api
module.exports = parser.parse(configPath);
View fib.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
module.exports = fibonacci;
 
process.on('message', function(m) {
var n = m.n;
var id = m.id;
var result;
if (n < 2) {
result = 1
} else {
result = fibonacci(n-2) + fibonacci(n-1)
}
process.send({id: id, result: result});
})
 
function fibonacci(n) {
if (n < 2)
return 1;
else
return fibonacci(n-2) + fibonacci(n-1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.