mirror of https://github.com/boa-dev/boa.git
Browse Source
* Add more utility functions around modules and exports * Use import instead of path * clippies and fmt * clippies and fmt * Add JsPromise::await_blocking and remove ell_and_run * Fix documentation CI jobpull/3956/head
Hans Larsen
3 months ago
committed by
GitHub
6 changed files with 253 additions and 2 deletions
@ -0,0 +1,26 @@
|
||||
/** |
||||
* Calculate the greatest common divisor of two numbers. |
||||
* @param {number} a |
||||
* @param {number} b |
||||
* @returns {number|*} The greatest common divisor of {a} and {b}. |
||||
* @throws {TypeError} If either {a} or {b} is not finite. |
||||
*/ |
||||
export function gcd(a, b) { |
||||
a = +a; |
||||
b = +b; |
||||
if (!Number.isFinite(a) || !Number.isFinite(b)) { |
||||
throw new TypeError("Invalid input"); |
||||
} |
||||
|
||||
// Euclidean algorithm
|
||||
function inner_gcd(a, b) { |
||||
while (b !== 0) { |
||||
let t = b; |
||||
b = a % b; |
||||
a = t; |
||||
} |
||||
return a; |
||||
} |
||||
|
||||
return inner_gcd(a, b); |
||||
} |
@ -0,0 +1,36 @@
|
||||
#![allow(unused_crate_dependencies)] |
||||
//! A test that mimics the GCD example from wasmtime.
|
||||
//! See: <https://docs.wasmtime.dev/examples-rust-gcd.html#gcdrs>.
|
||||
//! This is a good point to discuss and improve on the usability
|
||||
//! of the [`boa_engine`] API.
|
||||
|
||||
// You can execute this example with `cargo run --example gcd`
|
||||
|
||||
use boa_engine::{js_str, Context, Module}; |
||||
use boa_parser::Source; |
||||
use std::path::PathBuf; |
||||
|
||||
#[test] |
||||
fn gcd() { |
||||
let assets_dir = |
||||
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("tests/assets"); |
||||
|
||||
// Create the engine.
|
||||
let context = &mut Context::default(); |
||||
|
||||
// Load the JavaScript code.
|
||||
let gcd_path = assets_dir.join("gcd.js"); |
||||
let source = Source::from_filepath(&gcd_path).unwrap(); |
||||
let module = Module::parse(source, None, context).unwrap(); |
||||
module |
||||
.load_link_evaluate(context) |
||||
.await_blocking(context) |
||||
.unwrap(); |
||||
|
||||
let js_gcd = module |
||||
.get_typed_fn::<(i32, i32), i32>(js_str!("gcd"), context) |
||||
.unwrap(); |
||||
|
||||
assert_eq!(js_gcd.call(context, (6, 9)), Ok(3)); |
||||
assert_eq!(js_gcd.call(context, (9, 6)), Ok(3)); |
||||
} |
Loading…
Reference in new issue