forked from RafaCalderonR/pracWebWorker-Rafa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfizzBuzz.js
89 lines (71 loc) · 2.13 KB
/
fizzBuzz.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
class fizzBuzz {
constructor(view) {
this.view = view;
this.sectionForm = this.view.getElementById("form-section");
this.form = this.view.createElement("form");
this.workersInput = this.view.createElement("input");
this.workersInput.placeholder = "workers";
this.numberInput = this.view.createElement("input");
this.numberInput.placeholder = "num";
this.submitButton = this.view.createElement("button");
this.submitButton.textContent = "Start";
this.form.append(this.workersInput, this.numberInput, this.submitButton);
this.sectionForm.append(this.form);
this.getValues();
this.arrayResponse;
this.response = [];
}
get _workersInput() {
return this.workersInput.value;
}
get _numberInput() {
return this.numberInput.value;
}
resetForm() {
this.numberInput.value = "";
this.workersInput.value = "";
}
getValues() {
this.form.addEventListener("submit", event => {
event.preventDefault();
this.builderWorker(this._numberInput, this._workersInput);
});
}
pipe = (...functions) => initialValue =>
functions.reduce((value, funct) => funct(value), initialValue);
builderWorker(number, workers) {
const cuts = number / workers;
const arrayNumber = [...Array(Number(number)).keys()];
const workerGroup = [...Array(Number(workers))].map(
this.pipe(this.createWorker, this.asingAddEventListener)
);
const chunkArray = this.chunk(arrayNumber, cuts);
chunkArray.map((job, index) =>
workerGroup[index].postMessage({ index, job })
);
}
recieved = e => {
const { index, answer } = e.data;
this.response[index] = answer;
e.target.terminate();
this.display();
};
display = () => {
console.log(this.response);
};
createWorker() {
return new Worker("worker.js");
}
asingAddEventListener = worker => {
worker.addEventListener("message", this.recieved);
return worker;
};
chunk(array, size) {
if (!array.length) {
return [];
}
const head = array.slice(0, size);
const tail = array.slice(size);
return [head, ...this.chunk(tail, size)];
}
}