usim.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. (function (root, factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. // AMD. Register as an anonymous module.
  4. define([], factory);
  5. } else if (typeof module === 'object' && module.exports) {
  6. // Node. Does not work with strict CommonJS, but
  7. // only CommonJS-like environments that support module.exports,
  8. // like Node.
  9. module.exports = factory();
  10. } else {
  11. // Browser globals (root is window)
  12. root.uSim = factory();
  13. }
  14. }(this, function () {
  15. function uSim() {
  16. this.time = -Infinity;
  17. this.simcal = [];
  18. }
  19. uSim.prototype.schedule = function (time, object) {
  20. this.simcal.push({time: time, object: object});
  21. this.simcal.sort(function (a, b) {
  22. return a.time - b.time;
  23. });
  24. };
  25. var sentinel = {time: -Infinity, object: null};
  26. uSim.prototype.peekUntil = function (limit, cb) {
  27. var record = this.simcal.shift() || sentinel,
  28. recordTime = record.time;
  29. if (recordTime > limit) record = sentinel;
  30. else if (recordTime > this.time) this.time = recordTime;
  31. if (cb) cb(record.object); else return record.object;
  32. };
  33. uSim.prototype.peek = function (cb) {
  34. this.peekUntil(Infinity, cb);
  35. };
  36. uSim.prototype.streamUntil = function (limit, cb) {
  37. while (true) {
  38. var lastObject = null;
  39. this.peekUntil(limit, function (object) {
  40. lastObject = object;
  41. cb(object);
  42. });
  43. if (lastObject == null) break;
  44. }
  45. };
  46. uSim.prototype.stream = function (cb) {
  47. this.streamUntil(Infinity, cb);
  48. };
  49. uSim.prototype.run = function () {
  50. var self = this;
  51. this.stream(function (each) {
  52. each(self);
  53. });
  54. };
  55. return uSim;
  56. }));