Skip to content

Commit

Permalink
Use the module pattern in worker.js
Browse files Browse the repository at this point in the history
  • Loading branch information
fhd committed Apr 17, 2012
1 parent cf2b318 commit 279e912
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 27 deletions.
46 changes: 24 additions & 22 deletions public/js/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});
};
})();
26 changes: 21 additions & 5 deletions public/test/tests/sorting/worker.js
Expand Up @@ -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.