Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/hexagon6/collatz-wasm
https://github.com/hexagon6/collatz-wasm
Last synced: about 1 month ago
JSON representation
- Host: GitHub
- URL: https://github.com/hexagon6/collatz-wasm
- Owner: hexagon6
- Created: 2021-08-07T17:34:28.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2021-10-09T21:41:47.000Z (about 3 years ago)
- Last Synced: 2024-05-20T00:14:39.009Z (8 months ago)
- Language: JavaScript
- Size: 10.7 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# collatz-wasm
1. pick a positive integer number
2. a) when odd: 3x + 1
2. b) when even: x/2
3. repeat until you find a number you had beforeon positive integers this algorithm (the mathematical equivalent is called [Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture)) ends always at 1
![XKCD Collatz Conjecture](https://imgs.xkcd.com/comics/collatz_conjecture.png)
> it is an unsolved mathematical problem, but you could give it a try in the browser or another system which can run wasm with this module ;-)
> it accepts any javascript number (internally i32) and gives back an Array of numbers
## usage
By installing from [npm](https://www.npmjs.com/package/collatz-wasm)
`npm install collatz-wasm`
and by using a bundler you should be able to import it in javascript like this:
```javascript
import init, { collatz } from "collatz-wasm"...
init()
.then(() => {
collatz(1337)
})
```## plans for the future
I plan on adding support for i64 (javascript BigInt), but have not yet reached a proper understanding of Rust Traits to do so. An alternative would be to copy code and replace i32 with i64, but who would do such a thing??
## uses
The Collatz Conjecture can be used to plot nice graphs and art, which was a motivation to create this module
## building from rust to wasm
### install dependencies
First install a rust environment (e.g. rustup)
and then install wasm-pack like-a-so: `$ cargo install wasm-pack`
### build wasm bundle
> based on this howto: https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_wasm`$ wasm-pack build --target web`
This builds the rust lib.rs into a file bundle at `pkg/` which is ready to be imported into a javascript environment that has wasm support.
### using it locally from the git repository
```javascript
import init, { collatz } from "./pkg/collatz_wasm.js"
init()
.then(() => {
const list = Array.from(collatz(10))
console.log(JSON.stringify(list))
})
```### test wasm bundle locally
Start a local webserver (e.g. `python3 -m http.server`) and navigate to index.html to see a test page importing the compiled wasm (open Developer Tools to see result logged in the Javascript console).