Skip to content

Instantly share code, notes, and snippets.

@jay18001
Created December 28, 2017 05:14
Show Gist options
  • Save jay18001/d4dc5e7bac0e44eefe493ddb016ea741 to your computer and use it in GitHub Desktop.
Save jay18001/d4dc5e7bac0e44eefe493ddb016ea741 to your computer and use it in GitHub Desktop.
Square Root With WebAssembly
#include <stdio.h>
#include <stdint.h>
#include <emscripten/emscripten.h>
double EMSCRIPTEN_KEEPALIVE sq_root(double count) {
if (count == 0) {
return 1;
} else if (count == 1) {
return 2;
}
return count * count;
}
<!doctype html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Emscripten-Generated Code</title>
</head>
<body>
<button class="mybutton">Run myFunction</button>
<p id="count">0</p>
<script type='text/javascript'>
function toFixed(x) {
if (Math.abs(x) < 1.0) {
var e = parseInt(x.toString().split('e-')[1]);
if (e) {
x *= Math.pow(10,e-1);
x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);
}
} else {
var e = parseInt(x.toString().split('+')[1]);
if (e > 20) {
e -= 20;
x /= Math.pow(10,e);
x += (new Array(e+1)).join('0');
}
}
return x;
}
document.querySelector('.mybutton').addEventListener('click', function(){
var number = document.getElementById("count").innerHTML;
var result = _sq_root(number);
if (result == Infinity) {
result = 0;
}
document.getElementById('count').innerHTML = toFixed(result);
});
</script>
<script async type="text/javascript" src="SqureRoot.js"></script>
</body>
</html>
@jay18001
Copy link
Author

emcc -o SquareRoot.js SquareRoot.c -O3 -s WASM=1 -s NO_EXIT_RUNTIME=1 -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall"]'

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