Browse Source

first implementation

Herbert Vojčík 8 years ago
parent
commit
c4c457eefb
1 changed files with 49 additions and 1 deletions
  1. 49 1
      lib/usim.js

+ 49 - 1
lib/usim.js

@@ -12,5 +12,53 @@
         root.uSim = factory();
     }
 }(this, function () {
-    return {};
+    function uSim() {
+        this.time = -Infinity;
+        this.simcal = [];
+    }
+
+    uSim.prototype.schedule = function (time, object) {
+        this.simcal.push({time: time, object: object});
+        this.simcal.sort(function (a, b) {
+            return a.time - b.time;
+        });
+    };
+
+    var sentinel = {time: -Infinity, object: null};
+
+    uSim.prototype.peekUntil = function (limit, cb) {
+        var record = this.simcal.shift() || sentinel,
+            recordTime = record.time;
+        if (recordTime > limit) record = sentinel;
+        else if (recordTime > this.time) this.time = recordTime;
+        if (cb) cb(record.object); else return record.object;
+    };
+
+    uSim.prototype.peek = function (cb) {
+        this.peekUntil(Infinity, cb);
+    };
+
+    uSim.prototype.streamUntil = function (limit, cb) {
+        while (true) {
+            var lastObject = null;
+            this.peekUntil(limit, function (object) {
+                lastObject = object;
+                cb(object);
+            });
+            if (lastObject == null) break;
+        }
+    };
+
+    uSim.prototype.stream = function (cb) {
+        this.streamUntil(Infinity, cb);
+    };
+
+    uSim.prototype.run = function () {
+        var self = this;
+        this.stream(function (each) {
+            each(self);
+        });
+    };
+
+    return uSim;
 }));