---
# System prepended metadata

title: AssemblyScript
tags: [frontend, ' AssemblyScript', ' WebAssembly']

---

---
tags: frontend, WebAssembly, AssemblyScript
---
# AssemblyScript 
## Get start
https://www.assemblyscript.org/getting-started.html#setting-up-a-new-project

1. `npm init`
2. `npm install --save-dev assemblyscript`
3. `npx asinit .` 初始化, 記得要加 .
4. `npm run asbuild`
5. `npm test`
6. `npm start`

## Practice
1. Add more functions in ./assembly/index.ts
example:
* modify `.\assembly\index.ts`
```js
export function add(a: i32, b: i32): i32 {
  return a + b;
}

// Add a new function
export function fibonacci(v: i32): i32 {
  if (v === 1 || v === 2) return 1;
  return fibonacci(v - 1) + fibonacci(v - 2);
}

```

* Add a convenience script help build and test in `package.json`
```
  "scripts": {
    ...
    
    "bnt": "npm run asbuild:debug && npm run test"
  },
```
* Add some test in `./tests/index.js`

```javascript=
import assert from "assert";
import { add, fibonacci } from "../build/debug.js";

assert.strictEqual(add(1, 2), 3);

assert.strictEqual(fibonacci(1), 1);
assert.strictEqual(fibonacci(2), 1);
assert.strictEqual(fibonacci(3), 2);
assert.strictEqual(fibonacci(4), 3);
assert.strictEqual(fibonacci(5), 5);
assert.strictEqual(fibonacci(6), 8);
assert.strictEqual(fibonacci(7), 13);
assert.strictEqual(fibonacci(8), 21);
assert.strictEqual(fibonacci(9), 34);
assert.strictEqual(fibonacci(10), 55);

console.log("ok");

```
* Let's test!
`npm run bnt`
If everything is good, you should see "ok" on terminal.
![](https://i.imgur.com/z7Vl57S.png)


## About AssemblyScript you should know
1. Strictly typed
https://www.assemblyscript.org/concepts.html#strictly-typed
2. Import module
https://www.assemblyscript.org/concepts.html#sandboxed-execution

## AssemblyScript 從開始到放棄

AssemblyScript 並不相容 js 或 ts 的函式庫, 要重新改寫 crypto-js 整個函式庫顯然是不現實的..., 因此暫時放棄這個選項, 如果只是需要時做簡單的商業邏輯或許可以考慮使用 AssemblyScript, 但實作對稱加密...算了吧 orz