JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Run JavaScript Code One Magnitude Faster Using WebAssembly

Fang Jin
JavaScript in Plain English
5 min readJan 8, 2022

--

Photo by Mohammad Rahmani on Unsplash
const buildMaze = (data) => {
...
return { maze, startPos, numKeys }
}
const findMazeKeys = (maze, srcPos, keysTaken) => {
...
return dests
}
const findMazeSteps = (maze, startPos, numKeys) => {
const minMazeSteps = (srcPos, keysTaken) => {
...
return memo[memoKey]
}

let memo = {}, usage = 0, actual = 0
return minMazeSteps(startPos, [])
}
function World(data) {
const { maze, startPos, numKeys } = buildMaze(data)
return findMazeSteps(maze, startPos, numKeys)
}

The low-level language used, Rust

use std::collections::HashMap;#[derive(Debug,Hash,PartialEq,Eq,Copy,Clone)]
struct Pos(i8, i8);
type CharMat = Vec<Vec<char>>;
type MemoHash = HashMap<String, usize>;
struct Maze {
mat: CharMat,
origin: Pos,
keys_len: usize,
memo: MemoHash,
usage: usize,
actual: usize
}
impl Maze {
fn new(strs: &str) -> Maze {
...
Maze {
mat,
origin,
keys_len,
memo: HashMap::new(),
usage: 0,
actual: 0
}
}

fn locate_keys(
&self, p: &Pos, keys: &Vec<char>
) -> Vec<(char, Pos, usize)> {
...
dest
}

fn min_steps(
&mut self, p: &Pos, keys: &Vec<char>
) -> usize {
...
steps
}

fn solve(&mut self) -> usize {
let o = self.origin.clone();
self.min_steps(&o, &vec![]);
}
}

Speed up the high-level language, JavaScript

Meet the gap between the 50s and 5s, WebAssembly

import * as wasm from "world-interpretation"
console.log(wasm.run())

Summary

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Written by Fang Jin

Front-end Engineer, book author of “Designing React Hooks the Right Way” and "Think in Recursion"

Responses (4)

Write a response