Skip to content

Commit

Permalink
Add more complex lox example
Browse files Browse the repository at this point in the history
  • Loading branch information
0rphee committed Jan 22, 2025
1 parent b19955c commit 0c62e14
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
2 changes: 1 addition & 1 deletion web/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import {
PreopenDirectory,
} from "@bjorn3/browser_wasi_shim";
import { createEditorView } from "./editorconf.js";
import { originalLoxFileString } from "./loxexample.js";

function encode(str) {
return new TextEncoder().encode(str);
}

const loxFilename = "hello.lox";
const originalLoxFileString = `print "hello";\n`;
const loxFile = new File(
new TextEncoder("utf-8").encode(originalLoxFileString),
);
Expand Down
56 changes: 56 additions & 0 deletions web/src/loxexample.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const originalLoxFileString = `
// Base class for a Calculator
class Calculator {
compute(x) {
return x; // Default implementation
}
}
// Fibonacci calculator extends the base class
class Fibonacci < Calculator {
compute(n) {
if (n <= 1) return n;
return this.compute(n - 1) + this.compute(n - 2);
}
}
// Factorial calculator extends the base class
class Factorial < Calculator {
compute(n) {
if (n <= 1) return 1;
return n * this.compute(n - 1);
}
}
// Dynamic calculator handler
class DynamicCalculator {
init(calculator) {
this.calculator = calculator;
}
perform(input) {
return this.calculator.compute(input);
}
}
// Main execution
var input = 10;
fun showRes(name, func){
print name + " of";
print input;
print "results in:";
print func(input);
print "";
}
// Using a Fibonacci calculator
var fibCalculator = DynamicCalculator(Fibonacci());
showRes("Fibonacci", fibCalculator.perform);
// Using a Factorial calculator
var factCalculator = DynamicCalculator(Factorial());
showRes("Factorial", factCalculator.perform);
`;

export { originalLoxFileString };

0 comments on commit 0c62e14

Please sign in to comment.