Permalink
Browse files

Use the module pattern in worker.js

  • Loading branch information...
1 parent cf2b318 commit 279e9125cbf77c09d7c92b4f7a643a04411f2296 @fhd committed Apr 17, 2012
Showing with 45 additions and 27 deletions.
  1. +24 −22 public/js/sorting/worker.js
  2. +21 −5 public/test/tests/sorting/worker.js
@@ -1,25 +1,27 @@
-function sleep(ms) {
- var start = new Date().getTime();
- while (new Date().getTime() - start < ms);
-}
+(function() {
+ function makeNumeric(array) {
+ var i;
+ for (i = 0; i < array.length; i++)
+ array[i] = parseInt(array[i]);
+ }
-function update(array) {
- postMessage({"array": array, finished: false});
- sleep(200);
-}
+ sleep = function(ms) {
+ var start = new Date().getTime();
+ while (new Date().getTime() - start < ms);
+ }
-function makeNumeric(array) {
- var i;
- for (i = 0; i < array.length; i++)
- array[i] = parseInt(array[i]);
-}
+ update = function(array) {
+ postMessage({"array": array, finished: false});
+ sleep(200);
+ }
-onmessage = function(event) {
- var array = event.data.array,
- algorithm;
- makeNumeric(array);
- importScripts(event.data.file);
- algorithm = eval(event.data.functionName);
- algorithm(array);
- postMessage({"array": array, finished: true});
-}
+ onmessage = function(event) {
+ var array = event.data.array,
+ algorithm;
+ makeNumeric(array);
+ importScripts(event.data.file);
+ algorithm = eval(event.data.functionName);
+ algorithm(array);
+ postMessage({"array": array, finished: true});
+ };
+})();
@@ -22,8 +22,24 @@ test("update", 2, function() {
postMessage.restore();
});
-test("makeNumeric", 1, function() {
- var array = ["1", "2", "3"];
- makeNumeric(array);
- deepEqual(array, [1, 2, 3]);
-});
+test("onmessage", 3, function() {
+ f = sinon.stub();
+ importScripts = sinon.stub();
+ sinon.stub(window, "postMessage");
+
+ onmessage({data: {
+ array: ["1", "2", "3"],
+ file: "f.js",
+ functionName: "f"
+ }});
+
+ ok(importScripts.calledWith("f.js"),
+ "The supplied JS file should be loaded.");
+ ok(f.calledWith([1, 2, 3]),
+ "The sort function should be called with the array.");
+ ok(postMessage.calledWith({array: [1, 2, 3], finished: true}),
+ "The worker should post a message with the result.");
+
+ f = importScripts = undefined;
+ postMessage.restore();
+});

0 comments on commit 279e912

Please sign in to comment.