Skip to content

Commit ac2dc5d

Browse files
committed
feat(code): Wrote asm.js example
closes #12
1 parent b46d2f6 commit ac2dc5d

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ implementations are available
4646
* [dependency injection](src/14-dependency-injection.js)
4747
* [immutable data](src/15-immutable.js)
4848
* [async await](src/16-async-await.js)
49+
* [asm.js](src/17-asm.js)
4950

5051
[post]: http://glebbahmutov.com/blog/journey-from-procedural-to-reactive-javascript-with-stops/
5152

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,8 @@
5454
"node src/13-transducers.js",
5555
"node src/14-dependency-injection.js",
5656
"node src/15-immutable.js",
57-
"node src/16-async-await.js"
57+
"node src/16-async-await.js",
58+
"node src/17-asm.js"
5859
],
5960
"pre-push": [],
6061
"post-commit": [],

src/17-asm.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
'use asm';
2+
3+
// main point is to provide primitive type information
4+
// (unsigned bytes in this case) to the engine
5+
// by using typed arrays and '|0' operators on the individual variables
6+
7+
// Any suggestions for improving this Asm.js example are welcome
8+
// https://github.com/bahmutov/javascript-journey/issues
9+
10+
// numbers is an array of unsigned bytes
11+
var numbers = new Uint8Array([3, 1, 7]);
12+
// constant is an integer
13+
var constant = 2|0;
14+
15+
// multiplication of two integers
16+
function mul(a, b) {
17+
a = a|0;
18+
b = b|0;
19+
return a * b;
20+
}
21+
function print(n) {
22+
n = n|0;
23+
console.log(n);
24+
}
25+
var byConstant = mul.bind(null, constant);
26+
27+
function iterate(list, cb) {
28+
var n = list.length|0;
29+
var k = 0;
30+
for (; k < n; k += 1) {
31+
cb(list[k]|0);
32+
}
33+
}
34+
35+
// while v8 in node does not offer performance improvements,
36+
// other environments, like Firefox can
37+
var start = process.hrtime();
38+
iterate(numbers, byConstant);
39+
var elapsed = process.hrtime(start);
40+
console.log('multiplication took %d seconds %d nanoseconds',
41+
elapsed[0], elapsed[1]);
42+

0 commit comments

Comments
 (0)