Skip to content

Commit

Permalink
Lazily initialize Kernels
Browse files Browse the repository at this point in the history
  • Loading branch information
rameshvarun committed Sep 3, 2023
1 parent fd1e376 commit 50ae136
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/blog-cells.css
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,4 @@ script[type="text/notebook-cell"] {

margin-top: 25px;
margin-bottom: 25px;
}
}
32 changes: 28 additions & 4 deletions src/blog-cells.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,33 @@ import { JavaScriptKernel } from "./javascript-kernel";
import { PythonKernel } from "./python-kernel";
import { Kernel } from "./kernel";

const KERNELS: Map<string, Kernel> = new Map();
KERNELS.set("javascript", new JavaScriptKernel());
KERNELS.set("python", new PythonKernel());
// Register kernels by name and lazily initialize them.
class KernelFactory {
initializers: Map<string, () => Kernel> = new Map();
kernels: Map<string, Kernel> = new Map();

register(name: string, initializer: () => Kernel) {
this.initializers.set(name, initializer);
}

get(name: string): Kernel {
if (this.kernels.has(name)) {
return this.kernels.get(name)!;
}

if (this.initializers.has(name)) {
const kernel = this.initializers.get(name)!();
this.kernels.set(name, kernel);
return kernel;
}

throw new Error(`Unknown kernel: ${name}`);
}
}

const kernelFactory = new KernelFactory();
kernelFactory.register("javascript", () => new JavaScriptKernel());
kernelFactory.register("python", () => new PythonKernel());

class Cell extends React.Component<
{
Expand Down Expand Up @@ -204,7 +228,7 @@ domLoaded.then(() => {
const code = script.textContent?.trim() || "";

const kernelName = script.dataset.kernel || "javascript";
const kernel = KERNELS.get(kernelName)!;
const kernel = kernelFactory.get(kernelName);

const autoRun = script.dataset.autorun === "true";
const hidden = script.dataset.hidden === "true";
Expand Down
2 changes: 1 addition & 1 deletion src/python-kernel/worker.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
importScripts("https://cdn.jsdelivr.net/npm/pyodide@0.23.2/pyodide.min.js");
importScripts("https://cdn.jsdelivr.net/npm/pyodide@0.23.4/pyodide.min.js");
declare var loadPyodide;

let onStdout: ((str) => void) | null = null;
Expand Down

0 comments on commit 50ae136

Please sign in to comment.