Oktul home
  • English
  • Estonian

The documentation is in English only.

Contact us

Snippets: AssemblyScript

Oktul Code Studio snippets for AssemblyScript modules compiled to WebAssembly, as the console's Snippets dialog offers them.

These are the AssemblyScript snippets the console offers in a .as module. A module computes and reaches nothing: a script imports it and hands it copies of its arguments.

Sum a list of numbers

A function a script imports. A module gets copies of its arguments and reaches nothing else, so it can only compute.

export function sum(values: Float64Array): f64 {
let total: f64 = 0;
for (let i = 0; i < values.length; i++) total += unchecked(values[i]);
return total;
}

Hash a text

FNV-1a over a string, a fast way to compare long texts. Import it with import { fnv1a } from “./hash.as”.

export function fnv1a(text: string): u32 {
let hash: u32 = 0x811c9dc5;
for (let i = 0; i < text.length; i++) {
hash ^= <u32>text.charCodeAt(i);
hash *= 0x01000193;
}
return hash;
}

Score how alike two texts are

The edit distance between two strings, for finding near-duplicate summaries. It allocates nothing inside the loop.

export function distance(a: string, b: string): i32 {
const row = new Int32Array(b.length + 1);
for (let j = 0; j <= b.length; j++) row[j] = j;
for (let i = 1; i <= a.length; i++) {
let previous = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const current = row[j];
const cost = a.charCodeAt(i - 1) == b.charCodeAt(j - 1) ? 0 : 1;
row[j] = min(min(row[j] + 1, row[j - 1] + 1), previous + cost);
previous = current;
}
}
return row[b.length];
}

A problem or a question? Write to support@oktul.com or open a request in the Help Center (opens in a new tab).