Skip to content

Instantly share code, notes, and snippets.

@recmo
Last active June 1, 2017 14:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save recmo/e0b6911992897c5f51c38fda822537c2 to your computer and use it in GitHub Desktop.
Save recmo/e0b6911992897c5f51c38fda822537c2 to your computer and use it in GitHub Desktop.
WebAssembly compile and run example
/* 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