Factorial in WebAssembly

It seems your browser can't handle WebAssembly at the moment. The example below will not work.
If you have a recent Firefox or Chrome browser, you can enable it.

For Chrome

Go to chrome://flags/#enable-webassembly and enable WebAssembly.

For Firefox

Go to about:config, search for javascript.options.wasm and set it to true.

fact(5) =

Rust Code

#[no_mangle]
pub fn fact(mut n: i32) -> i32 {
    let mut result = 1;
    while n > 0 {
        result = result * n;
        n = n - 1;
    }
    result
}

Wasm Code

  (func $fact (type $rustfn-0-2) (param $0 i32) (result i32)
    (local $1 i32)
    (local $2 i32)
    (set_local $2
      (i32.load
        (i32.const 0)
      )
    )
    (set_local $1
      (i32.const 1)
    )
    (loop $shape$2$break $shape$2$continue
      (br_if $shape$2$break
        (i32.le_s
          (get_local $0)
          (i32.const 0)
        )
      )
      (set_local $1
        (i32.mul
          (get_local $1)
          (get_local $0)
        )
      )
      (set_local $0
        (i32.sub
          (get_local $0)
          (i32.const 1)
        )
      )
      (br $shape$2$continue)
    )
    (i32.store
      (i32.const 0)
      (get_local $2)
    )
    (get_local $1)
  )

Back