usim.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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[0] || sentinel,
  28. recordTime = record.time;
  29. if (recordTime > limit) record = sentinel;
  30. else this.simcal.shift();
  31. if (recordTime > this.time) this.time = recordTime;
  32. if (cb) cb(record.object); else return record.object;
  33. };
  34. uSim.prototype.peek = function (cb) {
  35. return this.peekUntil(Infinity, cb);
  36. };
  37. uSim.prototype.streamUntil = function (limit, cb) {
  38. while (true) {
  39. var lastObject = null;
  40. this.peekUntil(limit, function (object) {
  41. lastObject = object;
  42. cb(object);
  43. });
  44. if (lastObject == null) break;
  45. }
  46. };
  47. uSim.prototype.stream = function (cb) {
  48. this.streamUntil(Infinity, cb);
  49. };
  50. uSim.prototype.run = function () {
  51. var self = this;
  52. this.stream(function (each) {
  53. each(self);
  54. });
  55. };
  56. return uSim;
  57. }));