File tree Expand file tree Collapse file tree 8 files changed +619
-0
lines changed
Expand file tree Collapse file tree 8 files changed +619
-0
lines changed Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ package-lock.json
33LICENSE
44# this file is auto generated
55index.html
6+ wasm_exec.js
67# auto generated by esbuild
78minified-with-source-maps /bundle.js
89# auto generated by terser
Original file line number Diff line number Diff line change 1+ build :
2+ GOOS=js GOARCH=wasm tinygo build -o main.wasm ./main.go
3+ cp $(shell tinygo env TINYGOROOT) /targets/wasm_exec.js .
Original file line number Diff line number Diff line change 1+ Adapted from https://tinygo.org/docs/guides/webassembly/wasm/
Original file line number Diff line number Diff line change 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 >
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments