Skip to content

Commit 45173c5

Browse files
authored
Add go-wasm
1 parent e16d014 commit 45173c5

File tree

8 files changed

+619
-0
lines changed

8 files changed

+619
-0
lines changed

.prettierignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package-lock.json
33
LICENSE
44
# this file is auto generated
55
index.html
6+
wasm_exec.js
67
# auto generated by esbuild
78
minified-with-source-maps/bundle.js
89
# auto generated by terser

go-wasm/Makefile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
build:
2+
GOOS=js GOARCH=wasm tinygo build -o main.wasm ./main.go
3+
cp $(shell tinygo env TINYGOROOT)/targets/wasm_exec.js .

go-wasm/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Adapted from https://tinygo.org/docs/guides/webassembly/wasm/

go-wasm/index.html

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<html>
2+
<head>
3+
<meta charset="utf-8"/>
4+
<script src="wasm_exec.js"></script>
5+
<script>
6+
const go = new Go();
7+
WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
8+
go.run(result.instance);
9+
});
10+
</script>
11+
</head>
12+
<body>
13+
Check the console :)
14+
15+
To configure what Fibonacci to calculate, set the query param: "?n=30"
16+
</body>
17+
</html>

go-wasm/main.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"strconv"
6+
"syscall/js"
7+
"time"
8+
)
9+
10+
// recursiveFib calculates the Nth Fibonacci number using direct recursion.
11+
// This function has exponential time complexity.
12+
func recursiveFib(n int) int {
13+
if n <= 1 {
14+
return n
15+
}
16+
17+
return recursiveFib(n-1) + recursiveFib(n-2)
18+
}
19+
20+
func main() {
21+
// Default to 35
22+
n := 35
23+
24+
window := js.Global()
25+
location := window.Get("location")
26+
searchParams := window.Get("URLSearchParams").New(location.Get("search"))
27+
nParam := searchParams.Call("get", "n")
28+
if nParam.Type() == js.TypeString && nParam.String() != "" {
29+
parsed, err := strconv.Atoi(nParam.String())
30+
if err == nil {
31+
n = parsed
32+
}
33+
}
34+
35+
fmt.Printf("Calculating Fibonacci(%d)...\n", n)
36+
37+
start := time.Now()
38+
result := recursiveFib(n)
39+
elapsed := time.Since(start)
40+
41+
fmt.Printf("Result: %d\n", result)
42+
fmt.Printf("Time taken: %s\n", elapsed)
43+
}

go-wasm/main.wasm

609 KB
Binary file not shown.

0 commit comments

Comments
 (0)