Last active
June 1, 2017 14:55
-
-
Save recmo/e0b6911992897c5f51c38fda822537c2 to your computer and use it in GitHub Desktop.
WebAssembly compile and run example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global WebAssembly */ | |
import wast2wasm from 'wast2wasm'; | |
// Run with: babel-node --expose-wasm ./wasm.js | |
const wast = `(module | |
(func $fac (param i32) (result i32) | |
get_local 0 | |
i32.eqz | |
if i32 | |
i32.const 1 | |
else | |
get_local 0 | |
get_local 0 | |
i32.const 1 | |
i32.sub | |
call 0 | |
i32.mul | |
end | |
) | |
(export "main" (func $fac)) | |
)`; | |
const wasmImports = {}; | |
const compile = async (source) => { | |
const result = await wast2wasm(source); | |
const wasm = new Buffer(result.buffer); | |
console.log(`0x${wasm.toString('hex')}`); | |
console.log(wasm.toString('ascii')); | |
const module = new WebAssembly.Module(wasm); | |
const instance = new WebAssembly.Instance(module, wasmImports); | |
return instance.exports; | |
}; | |
const asyncMain = async () => { | |
const { main } = await compile(wast); | |
for (let i = 0; i < 30; ++i) { | |
console.log(i, main(i)); | |
} | |
}; | |
asyncMain(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment