analyze.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. var script = process.cwd() + '/' + process.argv[2];
  2. var spawn = require('child_process').spawn;
  3. var numbers = [];
  4. var boringResults = 0;
  5. var scriptRuns = 0;
  6. function runScript() {
  7. scriptRuns++;
  8. var child = spawn(process.execPath, [script]);
  9. var buffer = '';
  10. child.stdout.on('data', function(chunk) {
  11. buffer += chunk;
  12. var offset;
  13. while ((offset = buffer.indexOf('\n')) > -1) {
  14. var number = parseInt(buffer.substr(0, offset), 10);
  15. buffer = buffer.substr(offset + 1);
  16. var maxBefore = max();
  17. var minBefore = min();
  18. numbers.push(number);
  19. if (maxBefore === max() && minBefore === min()) {
  20. boringResults++;
  21. }
  22. if (boringResults > 10) {
  23. boringResults = 0;
  24. child.kill();
  25. runScript();
  26. }
  27. }
  28. });
  29. }
  30. function report() {
  31. console.log(
  32. 'max: %s | median: %s | sdev: %s | last: %s | min: %s | runs: %s | results: %s',
  33. max(),
  34. median(),
  35. sdev(),
  36. numbers[numbers.length - 1],
  37. min(),
  38. scriptRuns,
  39. numbers.length
  40. );
  41. }
  42. function min() {
  43. if (!numbers.length) return undefined;
  44. return numbers.reduce(function(min, number) {
  45. return (number < min)
  46. ? number
  47. : min;
  48. });
  49. }
  50. function max() {
  51. if (!numbers.length) return undefined;
  52. return numbers.reduce(function(max, number) {
  53. return (number > max)
  54. ? number
  55. : max;
  56. });
  57. }
  58. function median() {
  59. return numbers[Math.floor(numbers.length / 2)];
  60. }
  61. function sdev() {
  62. if (!numbers.length) return undefined;
  63. return Math.round(Math.sqrt(variance()));
  64. }
  65. function variance() {
  66. var t = 0, squares = 0, len = numbers.length;
  67. for (var i=0; i<len; i++) {
  68. var obs = numbers[i];
  69. t += obs;
  70. squares += Math.pow(obs, 2);
  71. }
  72. return (squares/len) - Math.pow(t/len, 2);
  73. }
  74. setInterval(report, 1000);
  75. runScript();