Created
April 13, 2017 11:37
-
-
Save HenriqueLimas/d322d4b84ce51ac6142eaed642c2d584 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const cluster = require('cluster') | |
const Cluster = cluster => { | |
return { | |
map (fn) { | |
return Cluster(fn(cluster)) | |
}, | |
valueOf() { | |
return cluster | |
} | |
} | |
} | |
const Empty = () => ({ | |
map: () => Empty() | |
}) | |
const master = cluster => cluster.isMaster | |
const worker = cluster => cluster.isWorker | |
const ifCondition = condition => value => ({ | |
map: fn => condition(value.valueOf()) ? value.map(fn) : Empty() | |
}) | |
const ifMaster = ifCondition(master) | |
const ifWorker = ifCondition(worker) | |
const fork = cluster => cluster.fork() | |
const listen = worker => { | |
worker.on('message', msg => { | |
if (msg.cmd === 'count') { | |
console.log(msg.value) | |
} else { | |
worker.kill() | |
} | |
}) | |
} | |
const countUntil = MAX => process => { | |
return new Promise(resolve => { | |
let count = 0 | |
setInterval(() => { | |
if (count < MAX) { | |
process.send({cmd: 'count', value: count }) | |
} else { | |
process.send({}) | |
resolve() | |
} | |
count++ | |
}, 1000) | |
}) | |
} | |
const countUntil10 = countUntil(10) | |
const log = value => console.log(value) | |
const waitAndLog = wait => wait.then(() => log('Finished')) | |
const c = Cluster(cluster) | |
ifMaster(c) | |
.map(fork) | |
.map(listen) | |
ifWorker(c) | |
.map(countUntil10.bind(null, process)) | |
.map(waitAndLog) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment