Skip to content

Instantly share code, notes, and snippets.

@kalepail
Created March 16, 2023 21:17
Show Gist options
  • Save kalepail/fe90dd1502ac72b60b58307fb1e3e301 to your computer and use it in GitHub Desktop.
Save kalepail/fe90dd1502ac72b60b58307fb1e3e301 to your computer and use it in GitHub Desktop.
ChatGPT-4 WASM vs JS test

Creating a complete Rust-based WebAssembly app to calculate the nth prime number involves several steps. First, you'll need to create the Rust code for the prime number calculation, then compile it to WebAssembly, and finally, create an HTML file that uses the compiled WebAssembly module.

Install Rust and its WebAssembly target:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustup target add wasm32-unknown-unknown

Create a new Rust library:

cargo new --lib nth_prime_wasm
cd nth_prime_wasm

Add wasm-bindgen to your Cargo.toml:

[dependencies]
wasm-bindgen = "0.2"

[lib]
crate-type = ["cdylib"]

Replace the contents of src/lib.rs with the following Rust code:

use wasm_bindgen::prelude::*;

fn is_prime(n: u32) -> bool {
    if n <= 1 {
        return false;
    }
    for i in 2..n {
        if n % i == 0 {
            return false;
        }
    }
    true
}

fn nth_prime(n: u32) -> u32 {
    let mut count = 0;
    let mut num = 0;
    while count < n {
        num += 1;
        if is_prime(num) {
            count += 1;
        }
    }
    num
}

#[wasm_bindgen]
pub fn calculate_nth_prime(n: u32) -> u32 {
    nth_prime(n)
}

Build the WebAssembly binary:

cargo install wasm-bindgen-cli
cargo build --target wasm32-unknown-unknown --release
wasm-bindgen --out-dir ./pkg --target web --no-typescript target/wasm32-unknown-unknown/release/nth_prime_wasm.wasm

Create an index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nth Prime WebAssembly App</title>
</head>
<body>
    <h1>Nth Prime WebAssembly App</h1>
    <input type="number" id="input" placeholder="Enter a positive integer">
    <button id="submit">Calculate Nth Prime</button>
    <p id="result"></p>
    <script type="module">
        import init, { calculate_nth_prime } from './pkg/nth_prime_wasm.js';

        async function run() {
            await init();

            const input = document.getElementById('input');
            const submit = document.getElementById('submit');
            const result = document.getElementById('result');

            submit.addEventListener('click', () => {
                const n = parseInt(input.value);
                if (!isNaN(n) && n > 0) {
                    const prime = calculate_nth_prime(n);
                    result.textContent = `The ${n}${n % 10 === 1 && n !== 11 ? "st" : n % 10 === 2 && n !== 12 ? "nd" : n % 10 === 3 && n !== 13 ? "rd" : "th"} prime number is ${prime}.`;
                } else {
                    result.textContent = 'Please enter a positive integer.';
                }
            });
        }

        run();
    </script>
</body>
</

I apologize for the confusion. It seems there was a formatting issue in the provided Cargo.toml. Please replace the contents of your Cargo.toml file with the following:

[package]
name = "nth_prime_wasm"
version = "0.1.0"
edition = "2018"

[dependencies]
wasm-bindgen = "0.2"

[lib]
crate-type = ["cdylib"]

This should resolve the error you encountered.

To compare the performance of the Rust WebAssembly function and a pure JavaScript function, you can add a JavaScript implementation for calculating the nth prime number and measure the execution time for both functions.

Update the index.html file with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nth Prime WebAssembly App</title>
</head>
<body>
    <h1>Nth Prime WebAssembly App</h1>
    <input type="number" id="input" placeholder="Enter a positive integer">
    <button id="submit">Calculate Nth Prime</button>
    <p id="result"></p>
    <script type="module">
        import init, { calculate_nth_prime as wasm_calculate_nth_prime } from './pkg/nth_prime_wasm.js';

        async function run() {
            await init();

            const input = document.getElementById('input');
            const submit = document.getElementById('submit');
            const result = document.getElementById('result');

            function is_prime(n) {
                if (n <= 1) {
                    return false;
                }
                for (let i = 2; i < n; i++) {
                    if (n % i === 0) {
                        return false;
                    }
                }
                return true;
            }

            function nth_prime(n) {
                let count = 0;
                let num = 0;
                while (count < n) {
                    num += 1;
                    if (is_prime(num)) {
                        count += 1;
                    }
                }
                return num;
            }

            submit.addEventListener('click', () => {
                const n = parseInt(input.value);
                if (!isNaN(n) && n > 0) {
                    // WebAssembly execution
                    const wasm_start = performance.now();
                    const wasm_prime = wasm_calculate_nth_prime(n);
                    const wasm_end = performance.now();
                    const wasm_duration = wasm_end - wasm_start;

                    // JavaScript execution
                    const js_start = performance.now();
                    const js_prime = nth_prime(n);
                    const js_end = performance.now();
                    const js_duration = js_end - js_start;

                    // Display results
                    result.innerHTML = `
                        <p>The ${n}${n % 10 === 1 && n !== 11 ? "st" : n % 10 === 2 && n !== 12 ? "nd" : n % 10 === 3 && n !== 13 ? "rd" : "th"} prime number is ${js_prime}.</p>
                        <p>JavaScript execution time: ${js_duration.toFixed(2)} ms</p>
                        <p>WebAssembly execution time: ${wasm_duration.toFixed(2)} ms</p>
                    `;
                } else {
                    result.textContent = 'Please enter a positive integer.';
                }
            });
        }

        run();
    </script>
</body>
</html>

Now, the JavaScript function for calculating the nth prime number is added, and the execution times for both the WebAssembly and JavaScript functions are displayed on the page.x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment