Skip to content

Commit

Permalink
formatted
Browse files Browse the repository at this point in the history
  • Loading branch information
duart38 committed Mar 14, 2021
1 parent eff856f commit ada954b
Show file tree
Hide file tree
Showing 14 changed files with 299 additions and 243 deletions.
26 changes: 13 additions & 13 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Deno",
"type": "pwa-node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "deno",
"runtimeArgs": ["run", "--inspect-brk", "-A", "${file}"],
"attachSimplePort": 9229
}
]
}
"version": "0.2.0",
"configurations": [
{
"name": "Deno",
"type": "pwa-node",
"request": "launch",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "deno",
"runtimeArgs": ["run", "--inspect-brk", "-A", "${file}"],
"attachSimplePort": 9229
}
]
}
16 changes: 8 additions & 8 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// .vscode/settings.json
{
"deno.enable": true,
"[typescript]": {
"editor.defaultFormatter": "denoland.vscode-deno",
},
"[typescriptreact]": {
"editor.defaultFormatter": "denoland.vscode-deno",
},
}
"deno.enable": true,
"[typescript]": {
"editor.defaultFormatter": "denoland.vscode-deno"
},
"[typescriptreact]": {
"editor.defaultFormatter": "denoland.vscode-deno"
}
}
172 changes: 94 additions & 78 deletions Thread.bundle.js
Original file line number Diff line number Diff line change
@@ -1,87 +1,103 @@
const importMeta = {
url: "file:///Users/duartasnel/Local/personal_projects/runLater/Thread.ts",
main: import.meta.main
url: "file:///Users/duartasnel/Local/personal_projects/runLater/Thread.ts",
main: import.meta.main,
};
class Thread {
importsMod = [];
stopped = false;
constructor(operation, type, imports){
imports?.forEach((v)=>{
if (v.endsWith(".ts'") || v.endsWith('.ts"')) {
throw new Error("Threaded imports do no support typescript files");
}
});
this.imports = imports || [];
this.filePath = this.createFile();
this.createImportsFolder();
this.populateFile(operation);
this.workerURL = new URL(this.filePath, importMeta.url);
this.worker = new Worker(this.workerURL.href.startsWith("http") ? "file:" + this.workerURL.pathname : this.workerURL.href, {
type
});
importsMod = [];
stopped = false;
constructor(operation, type, imports) {
imports?.forEach((v) => {
if (v.endsWith(".ts'") || v.endsWith('.ts"')) {
throw new Error("Threaded imports do no support typescript files");
}
});
this.imports = imports || [];
this.filePath = this.createFile();
this.createImportsFolder();
this.populateFile(operation);
this.workerURL = new URL(this.filePath, importMeta.url);
this.worker = new Worker(
this.workerURL.href.startsWith("http")
? "file:" + this.workerURL.pathname
: this.workerURL.href,
{
type,
},
);
}
createFile() {
return Deno.makeTempFileSync({
prefix: "deno_thread_",
suffix: ".js",
});
}
createImportsFolder() {
Deno.mkdirSync(this.getTempFolder() + "threaded_imports", {
recursive: true,
});
}
populateFile(code) {
this.imports?.forEach((val) => this.copyDep(val));
Deno.writeTextFileSync(
this.filePath,
`\n${
this.importsMod.join("\n")
}\nvar userCode = ${code.toString()}\n\nonmessage = function(e) {\n postMessage(userCode(e));\n}\n\n`,
);
}
copyDep(str) {
var importPathRegex = /('|"|`)(.+\.js)(\1)/ig;
var importInsRegex = /(import( |))({.+}|.+)(from( |))/ig;
var matchedPath = importPathRegex.exec(str) || "";
var file = false;
var fqfn = "";
if (
!matchedPath[0].includes("http://") &&
!matchedPath[0].includes("https://")
) {
file = true;
fqfn = matchedPath[0].replaceAll(/('|"|`)/ig, "");
}
createFile() {
return Deno.makeTempFileSync({
prefix: "deno_thread_",
suffix: ".js"
});
var matchedIns = importInsRegex.exec(str) || "";
if (!matchedIns) {
throw new Error(
"The import instruction seems to be unreadable try formatting it, for example: \n" +
"import { something } from './somet.js' \n ",
);
}
createImportsFolder() {
Deno.mkdirSync(this.getTempFolder() + "threaded_imports", {
recursive: true
});
if (file) {
this.importsMod.push(`${matchedIns[0]} "${Deno.realPathSync(fqfn)}"`);
} else {
this.importsMod.push(`${matchedIns[0]} ${matchedPath[0]}`);
}
populateFile(code) {
this.imports?.forEach((val)=>this.copyDep(val)
);
Deno.writeTextFileSync(this.filePath, `\n${this.importsMod.join("\n")}\nvar userCode = ${code.toString()}\n\nonmessage = function(e) {\n postMessage(userCode(e));\n}\n\n`);
}
copyDep(str) {
var importPathRegex = /('|"|`)(.+\.js)(\1)/ig;
var importInsRegex = /(import( |))({.+}|.+)(from( |))/ig;
var matchedPath = importPathRegex.exec(str) || "";
var file = false;
var fqfn = "";
if (!matchedPath[0].includes("http://") && !matchedPath[0].includes("https://")) {
file = true;
fqfn = matchedPath[0].replaceAll(/('|"|`)/ig, "");
}
var matchedIns = importInsRegex.exec(str) || "";
if (!matchedIns) throw new Error("The import instruction seems to be unreadable try formatting it, for example: \n" + "import { something } from './somet.js' \n ");
if (file) {
this.importsMod.push(`${matchedIns[0]} "${Deno.realPathSync(fqfn)}"`);
} else {
this.importsMod.push(`${matchedIns[0]} ${matchedPath[0]}`);
}
}
getTempFolder() {
let t = this.filePath;
return t.replace(/(\/\w+.js)/ig, "/");
}
postMessage(msg) {
this.worker.postMessage(msg);
return this;
}
stop() {
this.stopped = true;
this.worker.terminate();
}
remove() {
if (this.stopped == false) this.stop();
try {
return Deno.remove(this.filePath, {
recursive: true
});
} catch (err) {
console.error(`Failed to remove worker file: ${this.filePath}`);
console.error(err);
return Promise.reject(`Failed to remove worker file: ${this.filePath}`);
}
}
onMessage(callback) {
this.worker.onmessage = (e)=>callback(e.data)
;
return this;
}
getTempFolder() {
let t = this.filePath;
return t.replace(/(\/\w+.js)/ig, "/");
}
postMessage(msg) {
this.worker.postMessage(msg);
return this;
}
stop() {
this.stopped = true;
this.worker.terminate();
}
remove() {
if (this.stopped == false) this.stop();
try {
return Deno.remove(this.filePath, {
recursive: true,
});
} catch (err) {
console.error(`Failed to remove worker file: ${this.filePath}`);
console.error(err);
return Promise.reject(`Failed to remove worker file: ${this.filePath}`);
}
}
onMessage(callback) {
this.worker.onmessage = (e) => callback(e.data);
return this;
}
}
export { Thread as default };
44 changes: 27 additions & 17 deletions Thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,18 @@ export default class Thread<T> {
});
this.imports = imports || [];
this.filePath = this.createFile();
this.createImportsFolder()
this.createImportsFolder();
this.populateFile(operation);
this.workerURL = new URL(this.filePath, import.meta.url);

this.worker = new Worker(this.workerURL.href.startsWith("http") ? "file:"+this.workerURL.pathname : this.workerURL.href, {
type
});
this.worker = new Worker(
this.workerURL.href.startsWith("http")
? "file:" + this.workerURL.pathname
: this.workerURL.href,
{
type,
},
);
}
/**
* Creates the file that will house our worker
Expand All @@ -45,8 +50,10 @@ export default class Thread<T> {
* Creates folder in temp directory to house our imported files.
* This is purely to make cleanup easier
*/
private createImportsFolder(){
Deno.mkdirSync(this.getTempFolder() + "threaded_imports", {recursive: true})
private createImportsFolder() {
Deno.mkdirSync(this.getTempFolder() + "threaded_imports", {
recursive: true,
});
}

private populateFile(code: Function) {
Expand Down Expand Up @@ -82,12 +89,15 @@ onmessage = function(e) {
) {
file = true;
fqfn = matchedPath[0].replaceAll(/('|"|`)/ig, "");

}
var matchedIns = importInsRegex.exec(str) || ""; // matchedIns[0] > import {sss} from

if(!matchedIns) throw new Error("The import instruction seems to be unreadable try formatting it, for example: \n"
+"import { something } from './somet.js' \n ")

if (!matchedIns) {
throw new Error(
"The import instruction seems to be unreadable try formatting it, for example: \n" +
"import { something } from './somet.js' \n ",
);
}

if (file) {
this.importsMod.push(`${matchedIns[0]} "${Deno.realPathSync(fqfn)}"`); // returns the full path.
Expand All @@ -108,7 +118,7 @@ onmessage = function(e) {
* Sends data to the Thread
* @param msg
*/
public postMessage(msg: any): this{
public postMessage(msg: any): this {
this.worker.postMessage(msg);
return this;
}
Expand All @@ -125,12 +135,12 @@ onmessage = function(e) {
* Removes the current worker file from the temporary folder
* NOTE: Can be used while the program is running (calls stop()..)
*/
public remove(){
if(this.stopped == false) this.stop();
try{
return Deno.remove(this.filePath, {recursive: true});
}catch(err){
console.error(`Failed to remove worker file: ${this.filePath}`)
public remove() {
if (this.stopped == false) this.stop();
try {
return Deno.remove(this.filePath, { recursive: true });
} catch (err) {
console.error(`Failed to remove worker file: ${this.filePath}`);
console.error(err);
return Promise.reject(`Failed to remove worker file: ${this.filePath}`);
}
Expand Down
6 changes: 5 additions & 1 deletion egg.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@
"name": "Thread",
"description": "Type-safe multi-threading made 'easier'",
"stable": true,
"homepage": "https://github.com/duart38/Thread",
"entry": "./Thread.ts",
"version": "2.3.0",
"releaseType": "patch",
"files": [
"./LICENSE",
"./README.md",
"./Thread.ts",
"./Thread.bundle.js"
]
}
}
17 changes: 9 additions & 8 deletions examples/example_allot_of_threads.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import Thread from "../Thread.ts"
import Thread from "../Thread.ts";

let count = 13;

function postMessage(e: any){}
function postMessage(e: any) {}

function tester(){
function tester() {
let i = 0;
setInterval(()=>{
postMessage(0)
}, 500)
setInterval(() => {
postMessage(0);
}, 500);

return 0;
}

for(let i = 0; i < count; i++){
new Thread(tester, "module").onMessage((d)=>console.log(`thread -> ${i}`)).postMessage(0);
for (let i = 0; i < count; i++) {
new Thread(tester, "module").onMessage((d) => console.log(`thread -> ${i}`))
.postMessage(0);
}
Loading

0 comments on commit ada954b

Please sign in to comment.