Primes.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cprime.js 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. var spawn = require("child_process").spawn;
  2. function lineReader(stream, cb) {
  3. stream.on("data", function ondata(d) {
  4. d.toString().split("\n").forEach(str => {
  5. str = str.trim();
  6. if (str === "") return;
  7. cb(str);
  8. });
  9. });
  10. }
  11. module.exports = class CPrime {
  12. constructor(maxnum) {
  13. this.maxqueue = 30;
  14. this.maxnum = maxnum;
  15. this.queue = [];
  16. this.child = spawn("./cprime", [ maxnum ]);
  17. this.ready = false;
  18. lineReader(this.child.stderr, str => {
  19. console.log("stderr: "+str);
  20. if (str === "done" && !this.ready) {
  21. this.ready = true;
  22. }
  23. });
  24. lineReader(this.child.stdout, str => {
  25. if (this.queue.length === 0)
  26. return;
  27. var cb = this.queue.shift();
  28. cb(str);
  29. });
  30. }
  31. factor(num, cb) {
  32. num = num.replace(/\n/g, "");
  33. if (num.length > 1000)
  34. return cb("Invalid input.");
  35. if (!this.ready)
  36. return cb("Not ready.");
  37. if (this.queue.length >= this.maxqueue) {
  38. console.log("Warning: over "+this.maxqueue+" concurrent requests");
  39. return cb("Overloaded.");
  40. }
  41. this.queue.push(cb);
  42. this.child.stdin.write(num+"\n");
  43. }
  44. }